gpt4 book ai didi

ruby-on-rails - 运行在 Rails 4 和 MiniTest 中生成的功能测试时出现 InvalidAuthenticityToken 错误

转载 作者:行者123 更新时间:2023-11-28 21:09:55 25 4
gpt4 key购买 nike

在关注 http://guides.rubyonrails.org/testing.html 时并尝试针对我自动生成的 Controller 运行测试,这是我面临的错误。

Controller 和 Controller 的测试文件都是自动生成的。仅通过使 title 字段成为必需字段来对模型进行更改。

不确定我错过了什么。 Rails 服务器是否需要启动并运行才能运行功能测试?

错误日志

> rake test test/controllers/articles_controller_test.rb
Run options: --seed 43757

# Running:

E....

Finished in 0.467545s, 10.6942 runs/s, 10.6942 assertions/s.

1) Error:
ArticlesControllerTest#test_should_create_article:
ActionController::InvalidAuthenticityToken: ActionController::InvalidAuthenticityToken
test/controllers/articles_controller_test.rb:12:in `block (2 levels) in <class:ArticlesControllerTest>'
test/controllers/articles_controller_test.rb:10:in `block in <class:ArticlesControllerTest>'

5 runs, 5 assertions, 0 failures, 1 errors, 0 skips

articles_controller_test.rb

require 'test_helper'

class ArticlesControllerTest < ActionController::TestCase

setup do
@article = articles(:one)
end

test "should create article" do
assert_difference('Article.count') do
post :create, article: {body: @article.body, title: @article.title}
end
assert_redirected_to article_path(assigns(:article))
end

test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:articles)
end

..
...
end

文章.rb

class Article < ActiveRecord::Base
validates :title, presence: true
end

文章.yml

one:
title: MyString
body: MyText

two:
title: MyString
body: MyText

articles_controller.rb

class ArticlesController < ApplicationController

before_action :set_article, only: [:show, :edit, :update, :destroy]

# GET /articles
# GET /articles.json
def index
@articles = Article.all
end

# GET /articles/1
# GET /articles/1.json
def show
end

# GET /articles/new
def new
@article = Article.new
end

# GET /articles/1/edit
def edit
end

# POST /articles
# POST /articles.json
def create
@article = Article.new(article_params)

respond_to do |format|
if @article.save
format.html { redirect_to @article, notice: 'Article was successfully created.' }
format.json { render :show, status: :created, location: @article }
else
format.html { render :new }
format.json { render json: @article.errors, status: :unprocessable_entity }
end
end
end

..
....
end

最佳答案

我的错。一旦我将环境变量 RAILS_ENVdevelopment 切换到 test,所有测试都会通过。

关于ruby-on-rails - 运行在 Rails 4 和 MiniTest 中生成的功能测试时出现 InvalidAuthenticityToken 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35927779/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com