Sit back, relax, and enjoy the code.

Quick Hits: Setting the User Agent Header in Webrat

Posted: March 31st, 2009 | Author: Brad | Filed under: Rails, Testing, ruby | Tags: , , , , | 1 Comment »

If you’ve read the new PragProg beta e-book on RSpec, you may have read that you can set HTTP headers for your Webrat request like so:

Given /^I am browsing the site using Safari$/ do
  header "User-Agent" , "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_5_6; en-us)"
end

Like me, you may have found out the hard way that this doesn’t work. Webrat does not automagically apply these new HTTP headers to your request – they certainly don’t make it to my controller. What worked for me:

Given /^I am browsing the site using Safari$/ do
  headers["User-Agent"] = "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_5_6; en-us)"
end
 
When /^I visit my precious site$/ do
  get '/my/precious/path', my_query_string, headers
end

In the code above, headers is a method call that returns all the HTTP headers for your request. Just tack headers on as the third argument of your request, and you’re good to go.

  • Share/Bookmark

One Comment on “Quick Hits: Setting the User Agent Header in Webrat”

  1. #1 Custom User Agent with Cucumber Tests and Webrat in Mechanize Mode at Otaqui.Com said at 8:11 am on March 8th, 2010:

    [...] It’s pretty straightforward to set a custom user agent with mechanize if you’re using it directly, KickAssLabs has a good example. [...]


Leave a Reply