【问题标题】:How is a test throwing InvalidAuthenticityToken when forgery protection is disabled in the test environment?在测试环境中禁用伪造保护时,测试如何抛出 InvalidAuthenticityToken?
【发布时间】:2020-05-16 10:11:51
【问题描述】:

在我的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 文件中有什么?
  • @ellitt 我的test_helper.rb 文件包含 (1) SimpleCov 初始化,(2) 三行 ENV['RAILS_ENV'] ||= 'test'require_relative '../config/environment'require 'rails/test_help',以及 (3) class ActiveSupport::TestCase使用login_for_tests 方法通过我的SessionsController 进行登录。 SessionsController 具有 skip_before_action :verify_authenticity_token, only: :create,因此它也应该忽略身份验证令牌。

标签: ruby-on-rails ruby minitest


【解决方案1】:

由于我遇到了类似的问题,我花了一些时间才弄清楚这一点。

似乎由于某种原因该配置没有得到尊重,但将其放入您的 test_helper.rb 应该会有所帮助:

ApplicationController.allow_forgery_protection = false

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-26
    • 2016-03-04
    • 1970-01-01
    • 1970-01-01
    • 2019-03-07
    相关资源
    最近更新 更多