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.

Tags

, , , .

Related Posts

May 24th 2007 18:26 | comments (1)
 

Comments


Gravatar

topfunky

July 3rd 2007 20:57

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

Add Your Comments


(Required)

Your email address to get your Gravatar. Address itself is not shown.

(Include the http://)

(Required)

 

You Are Here


Douglas F Shearer

This is the homepage of Douglas F Shearer, a software developer and mountainbike racer. Find out more at the About page.

Gallery Latest


Side on Chips on crown Front on chip2 chip1 img67

Stay Informed


What is RSS?

Top Tags