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

NeptuneG · 2018年04月16日 · 最后由 NeptuneG 回复于 2018年04月17日 · 1185 次阅读

测试一个 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
需要 登录 后方可回复, 如果你还没有账号请 注册新账号