Douglas F Shearer

Mocking User_Agent In Rails Tests


Sometimes you may want to check the user agent of a request in your Rails controller, be this for checking for spam, or only allowing services such as Feedburner to access your RSS feeds. Something like this:


def feed
  if request.user_agent !~"Feedburner"
    # redirect to feedburner
  else
    # display feed
  end
end

So what happens when you try to test this using the standard Rails functional tests? You should see an error something like the following:


ActionView::TemplateError: undefined method `user_agent' for
 #<ActionController::TestRequest:0xb69d9b88>

Not so good. The solution is to add the following module to your app. I chose to add it in the same file as the appropriate controller, after the end statement for the class:


module ActionController
  class TestRequest < AbstractRequest
    attr_accessor :user_agent
  end
end

Now your tests should run fine, and you can even set the user agent as you wish in your tests:


def test_access_allowed_to_feedburner
  @request.user_agent = 'Feedburner'
  get :feed
  assert_response :success
end

Hope this helps you out.

 

Comments


Gravatar

topfunky

July 03 2007 20:57

Dropping it in test/test_helper.rb also worked for me.

Add Your Comments


Commenting is closed for this entry.

 

You Are Here


Douglas F Shearer

This is the homepage of Douglas F Shearer, a software developer and mountainbike racer. More…

Hire Me!


I'm available for hire. Ruby, Java and PHP work, both remotely (Worldwide) and locally (Scotland). Find out more or email me.

Flickr Latest


Stay Informed


What is RSS?

Categories


  1. Bike (93)
  2. Coding (85)
  3. Other (46)

Top Tags