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

时间:2016-03-10 21:35:56

标签: ruby-on-rails ruby-on-rails-4 testing functional-testing minitest

在关注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  

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

尝试将session[:_csrf_token] = SecureRandom.base64(32)添加到before do块,然后查看测试是否通过。