rails test仅在get请求中传递CSRF令牌

时间:2014-08-08 16:18:30

标签: ruby-on-rails unit-testing testing devise csrf

我正在尝试对我的控制器进行单元测试,每个使用get请求的测试都可以正常工作,但我在其中使用其他调用的测试(deletepost在create和put更新中)失败并带有:

WARNING: Can't verify CSRF token authenticity
Completed 401 Unauthorized in 2.5ms

例如,这是对destroy的测试:

  test "should destroy blog" do
    assert_difference('Blog.count', -1) do
      delete :destroy, id: @blog
    end

    assert_redirected_to blogs_path
  end

哪个不起作用

这是show的测试,有效:

  test "should show blog" do
    get :show, id: @blog
    assert_response :success
  end

在销毁测试中,设计authenticate_user!只是将我重定向到sign_in页面,测试失败。

2 个答案:

答案 0 :(得分:5)

显然在测试环境中禁用CSRF令牌是正常的, 我补充说:

  # Disable request forgery protection in test environment
  config.action_controller.allow_forgery_protection    = false

到我的" /config/environments/test.rb"文件和当前用户能够通过。

答案 1 :(得分:1)

要获得authenticate_user!,您需要包含并使用Devise测试助手,如下所示:

https://github.com/plataformatec/devise#test-helpers

class ActionController::TestCase
  include Devise::TestHelpers
end

在测试中使用它们:

  test "should show blog" do
    @user = users(:one) # or FactoryGirl.create(:user), or User.create!(email: 'foo@bar.com')
    sign_in @user
    get :show, id: @blog
    assert_response :success
  end

对于CSRF令牌,您的表单是使用form_for还是其他表单构建器构建的?

这些会自动将CSRF令牌添加到表单有效内容中。如果您使用<form>标记标记编写表单,则必须自己将其添加到表单中:

<%= hidden_field_tag :authenticity_token, form_authenticity_token %>