Search code examples
ruby-on-railsrubyrspecrspec-rails

RSpec: setting request headers


I'm trying to set important headers with ActionDispatch request helper method in my specs:

RSpec.describe API::V1::FoosController, type: :request do
  describe 'GET #index' do
    context 'common case' do
      request.env.merge!({'HTTP_FOO': 'FOO'})
      get api_foos_path, {}, {Accept: Mime::JSON}
    end
  end
end

But this header (and generally any header set with request) disappears when it comes to controller:

class API::V1::FoosController < ApplicationController
  respond_to :json, :xml

  def index
    request.env.has_key? 'HTTP_FOO' # false
    respond_with serialize_models(Foo.all)
  end
  # ...
end

Why does it happen and how do I set it properly? Setting the header with request.header or @request.header does the same.

P.S.: I know I can set headers as a third parameter of Rack::Test::Methods helpers, but I don't want to violate DRY - I'd like Mime formats only to be defined there.


Solution

  • Please try like this:

    request.env['HTTP_FOO_HEADER'] = 'foo header'