By default, protection against forgery is disabled on test environment for Rails applications.
If you have few test cases that need protection against forgery to be enabled, instead of changing the default option to true, you can enable it by mocking the ActionController::Base
instance.
Since there is no out of box solution to mock any instance of a given class the solutions presented will depend on external gems.
Mocking using Mocha
Make sure you have installed Mocha and then add the following line in the beginning of your test on in before
block:
Mocking using minitest-stub_any_instance
Install the minitest-stub_any_instance gem and include your test inside the following block:
Source
- This post is based on the RSpec solution for this problem presented on https://blog.tomoyukikashiro.me/post/test-csrf-in-feature-test-using-capybara.