How do I set HTTP_REFERER when testing in Rails?

Their recommendation translates to the following:

setup do
  @request.env['HTTP_REFERER'] = 'http://test.com/sessions/new'
  post :create, { :user => { :email => 'invalid@abc' } }
end

The accepted answer doesn't work for integration tests because the @request variable doesn't exist.

According to RailsGuides, you can pass headers to the helpers.

Rails <= 4:

test "blah" do
  get root_path, {}, {'HTTP_REFERER' => 'http://foo.com'}
  ...
end

Rails >= 5:

test "blah" do
  get root_path, params: { id: 12 }, headers: { "HTTP_REFERER" => "http://foo.com" }
  ...
end

In response to the question:

Why doesn't this work:

setup { post :create, { :user => { :email => 'invalid@abc' } }, 
{ 'referer' => '/sessions/new' } }

It doesn't work because the Rails doc you linked to documents a different class than the one you're probably using.

You linked to ActionController::Integration:Session. I'm guessing that you're writing a functional test (if you're using Test::Unit) or a controller test (if you're using Rspec). Either way, you're probably using ActionController::TestCase or a subclass thereof. Which, in turn, includes the module ActionController::TestProcess.

ActionController::TestProcess provides a get method with different parameters than the get method provided by ActionController::Integration:Session. (Annoying, eh?) The method signature is this:

 def get(action, parameters = nil, session = nil, flash = nil)

Sadly, there is no headers parameter. But at least setting @request.env['HTTP_REFERER'] works.


In Rails3 I got the same error:
To get rid of this in corresponding controller provided rescue for "redirect_to :back"

Example: redirect_to :back rescue redirect_to required_path