Edalol
Edalol

Reputation: 103

Unable to set headers in rails integration tests

I have an integration test

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

and then I have UsersController with method

  # GET /users/me
  def me
    puts headers
  end

and my output is

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

so for some reason the headers are not being set, I have also tried

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

or

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

but without any success and

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

is not accessible in the integrationTest

Upvotes: 5

Views: 2523

Answers (2)

Sebasti&#225;n Palma
Sebasti&#225;n Palma

Reputation: 33471

I've seen you can't have total access to your request.headers within your integration tests but you can validate them in your tests by using the headers option.

I've made this workaround; I've written index method which is validating the Authorization header is set on the request, like:

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

And in the tests I'm validating the presence and absence of this token just accessing to the headers and checking the value of the Authorization header, then for the status, and then for the error message given in the JSON response:

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

Upvotes: 2

fschuindt
fschuindt

Reputation: 841

Have you tried?

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

Upvotes: 3

Related Questions