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

房东的猫 提交于 2020-07-09 12:49:20

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/60940695/how-is-a-test-throwing-invalidauthenticitytoken-when-forgery-protection-is-disab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!