Rails disables CSRF protection in tests

Updated . Posted . Visible to the public. Repeats.

The default configuration Show archive.org snapshot of Rails disables CSRF protection Show archive.org snapshot in tests. If you accidentally forget to send the CSRF token for POST requests, your tests will be green even though your application is broken.

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

For RSpec feature tests

Add this to any file to the spec/support folder:

RSpec.configure do |config|
  config.around(type: :system, js: true) do |example|
    original = Rails.application.config.action_controller.allow_forgery_protection
    Rails.application.config.action_controller.allow_forgery_protection = true
    example.run
  ensure
    Rails.application.config.action_controller.allow_forgery_protection = original
  end
end

Also make sure you have configured RSpec to load all files in spec/support.

For Cucumber tests

Add this to any file in features/support:

Around '@javascript' do
  original = Rails.application.config.action_controller.allow_forgery_protection
  Rails.application.config.action_controller.allow_forgery_protection = true
  yield
ensure
  Rails.application.config.action_controller.allow_forgery_protection = original
end
Profile picture of Henning Koch
Henning Koch
Last edit
Henning Koch
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2013-10-08 12:58)