Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the referrer in an _integration_ test

Rspec can't access the HTTP referrer.

My user_sessions#create action contains: redirect_to :back, which Rails can only execute by reading the HTTP referrer.

Stackoverflow contains plenty of posts about how to set/mock/whatever the referrer in a controller spec. The general vibe is request.env["HTTP_REFERER"] = etc etc.

But I need redirect_to :back to work in an integration test that looks like this:

click_link "login"
page.current_path.should == "/login"
fill_in "user_session_email", :with => @user.email
fill_in "user_session_password", :with => @user.password
click_on "submit_user_session"
page.current_path.should == new_order_path
click_on "submit_order"

How can I do this?

Bonus points if the solution tells this spec to store the referral for every URL it visits (so the test is robust) and has no impact on other specs (for speed).

like image 819
steven_noble Avatar asked Mar 13 '14 10:03

steven_noble


People also ask

How do you set up a Referer?

If you want to change the referer (url) header that will be sent to the server when a user clicks an anchor or iframe is opened, you can do it without any hacks. Simply do history. replaceState, you will change the url as it will appear in the browser bar and also the referer that will be send to the server.

How do I get Referer from HTTP request?

It's available in the HTTP referer header. You can get it in a servlet as follows: String referrer = request. getHeader("referer"); // Yes, with the legendary misspelling.

How do I check my referrer policy?

Check If Referrer-Policy Is Enabled A quick way to check is to go to www.securityheaders.io and do a scan of your website. You can also check in FireFox's Developer Console.

What is document referrer?

document. referrer gives you the URI of the page that linked to the current page. This is a value that's available for all pages, not just frames. window. parent gives you the parent frame, and its location is its URI.


2 Answers

Capybara.current_session.driver.header 'Referer', 'http://example.com'

It looks like you're using Capybara, you can use Capybara to explicitly set the referer. You would have to update it whenever you wanted it to change, and if you needed to remove it you could set it to nil.

Maybe a bit cleaner:

referer = 'http://example.com'
Capybara.current_session.driver.header 'Referer', referer
like image 66
Ecnalyr Avatar answered Sep 20 '22 22:09

Ecnalyr


Here is the code used to implement the redirect_to method:

if referer = request.headers["Referer"]
  redirect_to(referer, :status=>status)
else
  raise RedirectBackError
end

Have you tried to set request.headers['Referer'] directly ?

like image 28
Pierre-Louis Gottfrois Avatar answered Sep 21 '22 22:09

Pierre-Louis Gottfrois