新手问题 如何在 ActionDispatch::IntegrationTest 中跳过 verify_authenticity_token?

NeptuneG · April 16, 2018 · Last by NeptuneG replied at April 17, 2018 · 1185 hits

测试一个 controller 时ActionDispatch::IntegrationTest中有以下的 case:

test "should success when received a request for javascript response" do
  get ajax_sample_path, headers: { "HTTP_ACCEPT" => "application/javascript" }
  assert_response :success
end

如果直接跑会报 402,但如果在相应的 controller 里加一句skip_before_action :verify_authenticity_token,测试就过了。

那么有可能在ActionDispatch::IntegrationTest中跳过verify_authenticity_token么?

在 environments/test.rb 加上 config.action_controller.allow_forgery_protection = false 來關閉 csrf token

感谢回答🙏

在 environments/test.rb 已经加过config.action_controller.allow_forgery_protection = false 最后查了一下Testing Rails Applications — Ruby on Rails Guides,加一个xhr: true参数后 OK 了

get ajax_sample_path, headers: { "HTTP_ACCEPT" => "application/javascript" }, xhr: true
You need to Sign in before reply, if you don't have an account, please Sign up first.