Enable CSRF protection in Javascript tests

Updated . Posted . Visible to the public.

You might not know that the default configuration Show archive.org snapshot of Rails disables CSRF protection Show archive.org snapshot in tests. This means that if you accidentally forget to send the CSRF token for non-GET requests, your tests will be green even though your application is completely broken (a failed CSRF check usually logs out the user). Rails probably does this because CSRF protection sort of requires Javascript.

You want to enable CSRF protection in tests that can speak Javascript.

For RSpec feature tests

Add this to any file in spec/support/:

RSpec.configure do |config|
  config.before(type: :feature, js: true) do
    allow_any_instance_of(ApplicationController).to receive(:protect_against_forgery?).and_return(true)
  end
end

For Cucumber tests

Add this to any file in features/support/:

Before '@javascript' do
  allow_any_instance_of(ApplicationController).to receive(:protect_against_forgery?).and_return(true)
end
Profile picture of Henning Koch
Henning Koch
Last edit
Niklas Hasselmeyer
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2013-10-08 12:58)