Ruby on Rails

Properly Setting HTTP_REFERER in a Rails Integration Test for a File Upload

This one had me frustrated for the past hour. I've been writing integration tests for a Rails project and got stuck on an error when I was trying to test that a file upload worked successfully and asserted a redirection was occuring correctly, but ran into the following error:

Expected response to be a <:redirect>, but was <500>
<"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\"].">

What a lovely error message to send me on a goose chase trying to set HTTP_REFERER directly on the @request as instructed.

Did Not Work

@request.env["HTTP_REFERER"] = '/'
post upload_path, { :file => fixture_file_upload("worddoc.docx", "application/msword") },
  { :html => {:multipart => true} }
assert_redirected_to '/', 'index'

This continued to spit out the same error. I finally stumbled across a post back from 2006 that held the answer. The HTTP_REFERER is not set the same way in an integration test:

Success!

post upload_path, { :file => fixture_file_upload("worddoc.docx", "application/msword") },
  { :html => {:multipart => true}, :referer => '/' }
assert_redirected_to '/', 'index'

Hope that saves anyone else some time if you encounter this error.

Author image

About Greg Jastrab

You've successfully subscribed to SmartLogic Blog
Great! Next, complete checkout for full access to SmartLogic Blog
Welcome back! You've successfully signed in.
Unable to sign you in. Please try again.
Success! Your account is fully activated, you now have access to all content.
Error! Stripe checkout failed.
Success! Your billing info is updated.
Error! Billing info update failed.