I'm simulating a request coming from an external service, which will not have an authenticity token. I want the test to fail if skip_before_action :verify_authenticity_token
is missing.
How do I do this from an Rspec request spec?
Currently I'm using post
as below, but it is happily accepted.
post endpoint, my_json_string, {'CONTENT_TYPE' => "application/json"}
CSRF protection disabled in test environment. Try to enable it use:
before do
ActionController::Base.allow_forgery_protection = true
end
after do
ActionController::Base.allow_forgery_protection = false
end
Disabling CSRF protection didn't work for me. So I created this module which uses the response body to retrieve the authenticity token:
https://gist.github.com/Rodrigora/440220a2e24bd42b7b0c
Then, I can test put/post requests without disabling forgery protection:
before do
@token = login(create(:user, password: 'password'))
end
it 'tests model creation' do
expect {
post_with_token 'path/to/model', model_params, @token
}.to change(Model, :count).by(1)
end
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