Rspec testing redirect_to :back

Cyrus picture Cyrus · May 18, 2011 · Viewed 20.4k times · Source

How do you test redirect_to :back in rspec?

I get

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"].

How do I go about setting the HTTP_REFERER in my test?

Answer

joshuarh picture joshuarh · Jul 18, 2011

Using RSpec, you can set the referer in a before block. When I tried to set the referer directly in the test, it didn't seem to work no matter where I put it, but the before block does the trick.

describe BackController < ApplicationController do
  before(:each) do
    request.env["HTTP_REFERER"] = "where_i_came_from"
  end

  describe "GET /goback" do
    it "redirects back to the referring page" do
      get 'goback'
      response.should redirect_to "where_i_came_from"
    end
  end
end