Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set HTTP_REFERER when testing in Rails?

I'm trying to test a controller and I got this error. I understand the error, but don't know how to fix it.

test: on CREATE to :user with completely invalid email should respond with    redirect (UsersControllerTest):ActionController::RedirectBackError:    No HTTP_REFERER was set in the request to this action,    so redirect_to :back could not be called successfully.  If this is a test, make sure to specify request.env["HTTP_REFERER"]. 

Specify it where? I tried this:

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

But got the same error.

Specify it with what, exactly? I guess the URI of the view I want it to go back to:

'/sessions/new' 

Is that what they mean?


OK, so it turns out they mean do this:

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

Can someone tell me where that's documented? I'd like to read up on the context of that information.

What if the domain is not "localhost:3000"? What if it's "localhost:3001" or something? Any way to anticipate that?

Why doesn't this work:

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

The Rails docs specifically say that's how you set the headers.

like image 361
Ethan Avatar asked Feb 12 '09 19:02

Ethan


2 Answers

Their recommendation translates to the following:

setup do   @request.env['HTTP_REFERER'] = 'http://test.com/sessions/new'   post :create, { :user => { :email => 'invalid@abc' } } end 
like image 176
James A. Rosen Avatar answered Oct 02 '22 03:10

James A. Rosen


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 
like image 27
Fotios Avatar answered Oct 02 '22 04:10

Fotios