Search code examples
rubyfirefoxseleniumselenium-webdriverwebautomation

Set user agent using Selenium 2


I am trying to web automate an application which behaves differently if accessed from a mobile device. Does anyone know the best way to achieve this using Selenium 2?

In an ideal world I would like to find a way to just configure the user agent so that we can easily test lots of permutations.


Solution

  • Looking here, it shows this code to set the user agent string in Firefox:

    FirefoxProfile profile = new FirefoxProfile();
    profile.addAdditionalPreference("general.useragent.override", "some UA string");
    WebDriver driver = new FirefoxDriver(profile);
    

    Converting to Ruby, it would look like this:

    require 'selenium-webdriver'
    
    profile = Selenium::WebDriver::Firefox::Profile.new
    profile['general.useragent.override'] = 'some UA string'
    
    driver = Selenium::WebDriver.for :firefox, :profile => profile
    

    Adding a line to the end of that to navigate to http://whatsmyuseragent.com indicates that it works as expected.

    However, Selenium 2 comes with drivers for both iPhones and Android applications. I haven't tried them yet, but it looks like they both run either in the simulators or in the real device. Is there a reason that these wouldn't work for you? They might give a better view of how things are really going to look on the device.