Enable Protect Against Forgery on MiniTest

How to enable Protect Against Forgery on Ruby on Rails tests using MiniTest

October 25, 2019 - 1 minute read -
Ruby Rails

By default, protection against forgery is disabled on test environment for Rails applications.

config.action_controller.allow_forgery_protection = false

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:

ActionController::Base
  .any_instance
  .expects(:protect_against_forgery?)
  .at_least_once
  .returns(true)

Mocking using minitest-stub_any_instance

Install the minitest-stub_any_instance gem and include your test inside the following block:

ActionController::Base.stub_any_instance(:protect_against_forgery?, true) do
  # add your test here
end
Source