简体   繁体   中英

rails test passing CSRF token only in get requests

I'm trying to unit-test my controllers, every test that uses the get request works fine, but the tests where I use other calls ( delete in destroy, post in create and put in update) fail with a:

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

for example this is the test for destroy:

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

    assert_redirected_to blogs_path
  end

which doesn't work

and this is the test for show, which works:

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

in the destroy test the devise authenticate_user! just redirects me to the sign_in page and the test fails.

Apparently it's a normal thing to disable the CSRF token in the test environment, I added:

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

to my "/config/environments/test.rb" file and the current user was able to pass through.

To get by authenticate_user! , you'll need to include and use the Devise test helpers as shown here:

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

class ActionController::TestCase
  include Devise::TestHelpers
end

And use them in your tests:

  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

As for the CSRF Token, is your form built using form_for or some other form-builder?

These automatically add the CSRF token to your form payload. If you are writing your forms with bare <form> tag markup, you'll have to add it to the form yourself like this:

<%= hidden_field_tag :authenticity_token, form_authenticity_token %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM