Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to POST with missing authenticity_token in rspec rails request test?

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"}
like image 636
James EJ Avatar asked Mar 09 '15 16:03

James EJ


2 Answers

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
like image 125
Maxim Avatar answered Nov 18 '22 02:11

Maxim


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
like image 43
Rodrigo Avatar answered Nov 18 '22 02:11

Rodrigo