【问题标题】:Unable to set headers in rails integration tests无法在 Rails 集成测试中设置标题
【发布时间】:2017-04-27 23:24:42
【问题描述】:

我有一个集成测试

class UsersTest < ActionDispatch::IntegrationTest
  test 'get  user' do    
    get '/users/me', headers: {'Authorization' => 'tokenvalue'}    
  end
end

然后我有带有方法的 UsersController

  # GET /users/me
  def me
    puts headers
  end

我的输出是

{"X-Frame-Options"=>"SAMEORIGIN", "X-XSS-Protection"=>"1; mode=block", "X-Content-Type-Options"=>"nosniff"}

所以由于某种原因没有设置标题, 我也试过了

get '/users/me', nil , headers: {'Authorization' => 'tokenvalue'}

get '/users/me', params: {}, headers: { HTTP_AUTHORIZATION: "token" }

但没有任何成功和

request.headers['HTTP_AUTHORIZATION'] = "token"  

在集成测试中无法访问

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-5 integration-testing


    【解决方案1】:

    你试过了吗?

    get '/users/me', nil, {'Authorization' =&gt; 'tokenvalue'}

    【讨论】:

    • 是的,输出还是一样的。
    • 顺便提一下,这是旧方法弃用警告:在集成测试中使用位置参数已被弃用,取而代之的是关键字参数,并将在 Rails 5.1 中删除
    • 是的,我确实收到了弃用警告,但它仍然不起作用。集成测试是否有可能丢弃 authz 标头?
    • 您是否需要在集成测试中访问您的request.headers?是否需要验证令牌是否存在?
    • 不,我没有,但在 users_controller 中我需要验证 authz 标头
    【解决方案2】:

    我发现您无法在集成测试中完全访问您的 request.headers,但您可以在测试中使用 headers 哈希选项访问它们来验证它们。

    我已经解决了这个问题,我有一个方法 index 验证在请求时正在设置 Authorization 标头,例如:

    def index
      if !request.headers['Authorization'].nil?
        @boxes = Box.all
      else
        render json: { error: 'no auth' }, status: :unauthorized
      end 
    end
    

    在测试中,我正在验证是否存在此令牌,只需访问 headers 并验证 Authorization 标头的值,然后验证状态,然后验证给出的错误消息在 JSON 响应中:

    test 'should get index if authorization is present' do
      get boxes_url, headers: { 'Authorization' => 'hallo' }
      assert_response :success
    end
    
    test 'should not get index if authorization is not present' do
      get boxes_url, headers: { 'Authorization' => nil }
      assert_response :unauthorized
      body = JSON.parse(response.body)
      assert_equal 'no auth', body['error']
    end
    

    【讨论】:

      猜你喜欢
      • 2012-02-01
      • 1970-01-01
      • 2012-12-09
      • 2013-03-22
      • 1970-01-01
      • 2017-09-27
      • 1970-01-01
      • 1970-01-01
      • 2017-09-19
      相关资源
      最近更新 更多