【问题标题】:How to POST with missing authenticity_token in rspec rails request test?如何在 rspec rails 请求测试中发布缺少authentity_token 的帖子?
【发布时间】:2015-05-10 22:02:17
【问题描述】:

我正在模拟来自外部服务的请求,该服务没有真实性令牌。如果skip_before_action :verify_authenticity_token 丢失,我希望测试失败。

如何根据 Rspec 请求规范执行此操作?

目前我正在使用post,如下所示,但很高兴接受。

post endpoint, my_json_string, {'CONTENT_TYPE' => "application/json"}

【问题讨论】:

    标签: ruby-on-rails rspec csrf authenticity-token


    【解决方案1】:

    CSRF 保护disabled in test environment。尝试启用它使用:

    before do
      ActionController::Base.allow_forgery_protection = true
    end
    
    after do
      ActionController::Base.allow_forgery_protection = false
    end
    

    【讨论】:

    • 从 Rails 4.2.5.1 和 Rspec 3.4 开始,这种技术可以正常工作。我怀疑这是实施解决方案的正确方法。
    • CSRF保护测试,可能需要the raise_error matcher:expect { post endpoint, my_json_string }.to raise_error(ActionController::InvalidAuthenticityToken)。我以为我应该检查响应的返回码。
    • 另外,行号在master分支上不再有效。使用this 之类的标签怎么样?
    • @FranklinYu:更新了链接。好建议。
    • 现在的 Rails 5 (API) 也是不错的解决方案。
    【解决方案2】:

    禁用 CSRF 保护对我不起作用。所以我创建了这个模块,它使用响应体来检索真实性令牌:

    https://gist.github.com/Rodrigora/440220a2e24bd42b7b0c

    然后,我可以在不禁用伪造保护的情况下测试 put/post 请求:

    before do
      @token = login(create(:user, password: 'password'))
    end
    
    it 'tests model creation' do
       expect {
         post_with_token 'path/to/model', model_params, @token
       }.to change(Model, :count).by(1)
    end
    

    【讨论】:

      猜你喜欢
      • 2018-10-03
      • 2011-10-10
      • 1970-01-01
      • 1970-01-01
      • 2016-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多