Search code examples
ruby-on-railsrubyminitest

How is a test throwing InvalidAuthenticityToken when forgery protection is disabled in the test environment?


In my ApplicationController, I have set:

protect_from_forgery with: :exception

In my config/environments/test.rb, I have set:

config.action_controller.allow_forgery_protection = false

My understanding is that this should prevent authenticity token checking. But when running my tests, my non-GET requests result in:

Minitest::UnexpectedError: ActionController::InvalidAuthenticityToken

If I comment out protect_from_forgery with: :exception, I no longer get the InvalidAuthenticityToken exception.

How could I be getting InvalidAuthenticityToken if allow_forgery_protection is set to false?

UPDATE: I know I can disable protection when running tests by using protect_from_forgery with: :exception unless Rails.env.test?. I'm asking why my attempt to disable it in my test environment config via allow_forgery_protection = false doesn't work.


Solution

  • Took me a while to figure this out as I was having a similar issue.

    It seems like the config was not being respected for some reason or another but putting this in your test_helper.rb should help:

    ApplicationController.allow_forgery_protection = false