It’s pretty straightforward to set a custom user agent with mechanize if you’re using it directly, KickAssLabs has a good example.
If you’re using Mechanize through Webrat though, things are a little different. The nice thing though, is that you can do this in a step definition – allowing features to be based on different browser scenarios (this is great if you’re developing across devices).
First off there are two accessors of interest in mechanize, “user_agent” and “user_agent_alias”. The former is fairly self evident and lets you define the user agent at will, the latter gives you shortcut access to a list of common user agents baked into mechanize. You can see that list in the mechanize.rb source. It contains some desktop browsers, the iPhone and the default Mechanize UA strings.
If you’re happy with the default alias list, you can just write a step definition like this:
Given /^I am using the "(.*)" browser$/ do |browser| webrat.adapter.mechanize.user_agent_alias = browser end
And then you can use this in your features:
Given I am using the "iPhone" browser When I visit the home page Then I should see "You are using an iPhone!"
If you want to be able to specify your own UA strings, and as I said this is especially likely if you are developing cross-device applications where capabilities are important, then you can just use your own hash instead, and set “user_agent” rather than “user_agent_alias”:
Given /^I am using the "(.*)" browser$/ do |browser|
UA_ALIASES = {
"Nokia N95" => "Mozilla/5.0 (SymbianOS/9.2; .....",
"Palm Pre" => "Mozilla/5.0 (webOS/1.0; ....."
}
webrat.adapter.mechanize.user_agent = UA_ALIASES[browser]
end
With a little tweaking you could use both the included list and, if the string from your feature isn’t there, look in a custom list too.