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.