无法在rails集成测试中设置标头

时间:2017-04-27 23:24:43

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

我有一个集成测试

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"  

在IntegrationTest中无法访问

2 个答案:

答案 0 :(得分:2)

你试过吗?

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

答案 1 :(得分:0)

我发现您无法在集成测试中完全访问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
相关问题