Rails only tests CSRF token in receive requests
I'm trying to unit test my controllers, every test that uses the request get
works fine, but the tests where I use other calls ( delete
in destroy, post
in create and put
in update) fail:
WARNING: Can't verify CSRF token authenticity
Completed 401 Unauthorized in 2.5ms
for example, this is a test for destruction:
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 a show test that works:
test "should show blog" do
get :show, id: @blog
assert_response :success
end
in the destroy test, the project authenticate_user!
just redirects me to the sign_in page and the test fails.
source to share
Apparently it's a common thing to disable CSRF token in a test environment, I added:
# Disable request forgery protection in test environment
config.action_controller.allow_forgery_protection = false
to my file "/config/environments/test.rb" and the current user was able to get through.
source to share
To get authenticate_user!
, you will need to enable and use the Devise Test Helpers as shown below:
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 CSRF token, is your form built with form_for
or some other form constructor?
They automatically add the CSRF token to your form payload. If you write your forms with open tag markup <form>
, you need to add it to the form yourself:
<%= hidden_field_tag :authenticity_token, form_authenticity_token %>
source to share