在测试环境中禁用伪造保护时,测试如何抛出 InvalidAuthenticityToken?
How is a test throwing InvalidAuthenticityToken when forgery protection is disabled in the test environment?
在我的 ApplicationController
中,我设置了:
protect_from_forgery with: :exception
在我的 config/environments/test.rb
中,我设置了:
config.action_controller.allow_forgery_protection = false
我的理解是,这应该会阻止真实性令牌检查。但是当 运行 我的测试时,我的非 GET
请求导致:
Minitest::UnexpectedError: ActionController::InvalidAuthenticityToken
如果我注释掉 protect_from_forgery with: :exception
,我将不再得到 InvalidAuthenticityToken
异常。
如果 allow_forgery_protection
设置为 false
,我怎么会得到 InvalidAuthenticityToken
?
更新: 我知道我可以在 运行 测试时使用 protect_from_forgery with: :exception unless Rails.env.test?
禁用保护。我在问为什么我尝试通过 allow_forgery_protection = false
在我的测试环境配置中禁用它不起作用。
我遇到了类似的问题,花了一段时间才弄明白。
配置似乎由于某种原因未被遵守,但将其放入您的 test_helper.rb 应该会有所帮助:
ApplicationController.allow_forgery_protection = false
在我的 ApplicationController
中,我设置了:
protect_from_forgery with: :exception
在我的 config/environments/test.rb
中,我设置了:
config.action_controller.allow_forgery_protection = false
我的理解是,这应该会阻止真实性令牌检查。但是当 运行 我的测试时,我的非 GET
请求导致:
Minitest::UnexpectedError: ActionController::InvalidAuthenticityToken
如果我注释掉 protect_from_forgery with: :exception
,我将不再得到 InvalidAuthenticityToken
异常。
如果 allow_forgery_protection
设置为 false
,我怎么会得到 InvalidAuthenticityToken
?
更新: 我知道我可以在 运行 测试时使用 protect_from_forgery with: :exception unless Rails.env.test?
禁用保护。我在问为什么我尝试通过 allow_forgery_protection = false
在我的测试环境配置中禁用它不起作用。
我遇到了类似的问题,花了一段时间才弄明白。
配置似乎由于某种原因未被遵守,但将其放入您的 test_helper.rb 应该会有所帮助:
ApplicationController.allow_forgery_protection = false