Features Controllers and HTTP_REFERER

October 29, 2008

Had a problem with a feature failing. Was getting an error

When I add a product to the cart                     # features/steps/cart_steps.rb:11
      Cannot redirect to nil! (ActionController::ActionControllerError)
      /Library/Ruby/Gems/1.8/gems/actionpack-2.1.1/lib/action_controller/base.rb:1044:in `redirect_to'

The additional huge stack trace led me to my cart controller. Here I was using the rather standard sort of code

respond_to do |format|
  format.html { redirect_to request.env["HTTP_REFERER"]} 
end

Problem is that in the test environment request.env["HTTP_REFERER"] is nil. We have a couple of choices

  1. Set HTTP_REFERER in the test environment
  2. Program defensively to deal with nil HTTP_REFERER

In the end did the second (mostly because couldn’t get first to work quickly)

  respond_to do |format|
    format.html { redirect_to referer} 
  end
...

private
def referer
 ref = request.env["HTTP_REFERER"]
 ref ||= '/products'
end

I actually quite like this solution.