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.
CSRF protection when plain vanilla Rails form is used On the server, Rails retrieves the token using params[:authenticity_token]. Rails checks if the token has been tampered with and if everything is fine then that request proceeds.
A CSRF token is a unique, secret, unpredictable value that is generated by the server-side application and transmitted to the client in such a way that it is included in a subsequent HTTP request made by the client.
To fetch a CRSF token, the app must send a request header called X-CSRF-Token with the value fetch in this call. The server generates a token, stores it in the user's session table, and sends the value in the X-CSRF-Token HTTP response header.
Briefly, Cross-Site Request Forgery (CSRF) is an attack that allows a malicious user to spoof legitimate requests to your server, masquerading as an authenticated user. Rails protects against this kind of attack by generating unique tokens and validating their authenticity with each submission.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With