Read more

How to set the user agent in tests

Arne Hartherz
March 25, 2013Software engineer at makandra GmbH

The User-Agent HTTP header identifies the client and is sent by "regular" browsers, search engine crawlers, or other web client software.

Cucumber

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

In Rack::Test, you can set your user agent like this on Capybara:

Given /^my user agent is "(.+)"$/ do |agent|
  page.driver.browser.header('User-Agent', agent)
  # Or, for older Capybaras:
  # page.driver.header('User-Agent', agent)
end

For Selenium tests with Firefox, it seems you can set the general.useragent.override profile setting to your preferred value. See StackOverflow Show archive.org snapshot for more information on that.
When you are using Chrome, you can spawn a new Chrome using the --user-agent command line switch.

RSpec

In controller specs, you can just modify the Rack environment before making your request:

request.env['HTTP_USER_AGENT'] = 'Googlebot'
get :index

Request specs have no request object. Instead, specify headers when performing the request:

get :index, headers: { HTTP_USER_AGENT: 'Googlebot' }
Posted by Arne Hartherz to makandra dev (2013-03-25 16:32)