在测试环境中禁用伪造保护时,测试如何抛出 InvalidAuthenticityToken? [英] How is a test throwing InvalidAuthenticityToken when forgery protection is disabled in the test environment?
问题描述
在我的 ApplicationController
中,我设置了:
In my ApplicationController
, I have set:
protect_from_forgery with: :exception
在我的 config/environments/test.rb
中,我设置了:
In my config/environments/test.rb
, I have set:
config.action_controller.allow_forgery_protection = false
我的理解是这应该会阻止真实性令牌检查.但是在运行我的测试时,我的非 GET
请求会导致:
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
如果我用 :exception 注释掉 protect_from_forgery,我将不再收到
InvalidAuthenticityToken
异常.
If I comment out protect_from_forgery with: :exception
, I no longer get the InvalidAuthenticityToken
exception.
如果 allow_forgery_protection
设置为 false
,我如何获得 InvalidAuthenticityToken
?
How could I be getting InvalidAuthenticityToken
if allow_forgery_protection
is set to false
?
更新:我知道我可以在运行测试时禁用保护,方法是使用 protect_from_forgery with: :exception until Rails.env.test?
.我在问为什么我尝试通过 allow_forgery_protection = 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.
推荐答案
我花了一段时间才弄明白,因为我遇到了类似的问题.
Took me a while to figure this out as I was having a similar issue.
似乎由于某种原因没有遵守配置,但将其放入 test_helper.rb 应该会有所帮助:
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
这篇关于在测试环境中禁用伪造保护时,测试如何抛出 InvalidAuthenticityToken?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!