Changes
-You might not know that Rails **[disables CSRF protection in tests](http://guides.rubyonrails.org/security.html#cross-site-request-forgery-csrf)**. 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 might not know that the [default configuration](https://github.com/rails/rails/blob/90a1eaa1b30ba1f2d524e197460e549c03cf5698/railties/lib/rails/generators/rails/app/templates/config/environments/test.rb.tt#L29) of Rails **disables [CSRF protection](http://guides.rubyonrails.org/security.html#cross-site-request-forgery-csrf) 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 Cucumber scenarios that can speak Javascript.** To do so, copy the attached file to `features/support`. For this to work you also need the following things:- +**You want to enable CSRF protection in tests that can speak Javascript.**
-1. [RSpec stubs and mocks in Cucumber](https://makandracards.com/makandra/696-using-rspec-stubs-and-mocks-in-cucumber)-2. [rspec_candy](https://github.com/makandra/rspec_candy)-3. [Cucumber: Detect if the current Capybara driver supports Javascript](https://makandracards.com/makandra/18787-cucumber-detect-if-the-current-capybara-driver-supports-javascript)-- +### For RSpec feature tests
- +Add this to any file in `spec/support/`:
- +```rb
- +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/`:
- +```rb
- +Before '@javascript' do
- + allow_any_instance_of(ApplicationController).to receive(:protect_against_forgery?).and_return(true)
- +end
- +```
- +
Posted by Niklas Hasselmeyer to makandra dev (2025-11-27 14:47)