Quick Hits: Setting the User Agent Header in Webrat
Posted: March 31st, 2009 | Author: Brad | Filed under: Rails, Testing, ruby | Tags: cucumber, Rails, rspec, ruby, webrat | 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.