【发布时间】:2016-03-10 21:35:55
【问题描述】:
在关注http://guides.rubyonrails.org/testing.html 并尝试对我的自动生成的控制器进行测试时,这是我面临的错误。
控制器和控制器的测试文件都是自动生成的。仅通过强制 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
article.rb
class Article < ActiveRecord::Base
validates :title, presence: true
end
articles.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
【问题讨论】:
-
检查
<%= csrf_meta_tags %>行是否存在于布局文件中,如stackoverflow.com/a/19819589/429758 中所述 -
<%= csrf_meta_tags %>存在于application.html.erb
标签: ruby-on-rails ruby-on-rails-4 testing functional-testing minitest