How to: Specify size of Selenium browser window

Updated . Posted . Visible to the public.

Applications often show or hide elements based on viewport dimensions, or may have components that behave differently (like mobile vs desktop navigation menus).
Since you want your integration tests to behave consistently, you want to set a specific size for your tests' browser windows.

Using WebDriver options / Chrome device metrics

For Google Chrome, the preferred way is setting "device metrics". This allows you to configure dimensions larger than your display and enable/disable touch behavior.

Simply use register_driver to set up a driver that you then connect to Capybara.
Here is an example for a desktop-like device.

Capybara.register_driver :selenium do |app|
  options = Selenium::WebDriver::Chrome::Options.new
  options.add_emulation(device_metrics: { width: 1440, height: 900, touch: false })
  Capybara::Selenium::Driver.new(app, browser: :chrome, options: options)
end

Then, simply switch the driver via Capybara.current_driver = :selenium.

If you use Cucumber for integration testing, wrap that into something like Before('@javascript') { ... }.

Benefits of using device metrics are:

  • You can configure any device resultion and are not limited by minimum/maximum window size. (Chrome's minimum is much wider than most phones).
  • You can use Chrome's predefined list of devices that comes with settings for resolution, DPI, and touch capabilities. Example:
Capybara.register_driver :mobile_selenium do |app|
  options = SeleniumHelpers.shared_driver_options
  options.add_emulation(device_name: 'iPhone X')
  Capybara::Selenium::Driver.new(app, browser: :chrome, options: options)
end

Note that the rendered viewport may be larger than Chrome's browser window. This can be confusing when trying to debug and manually interact with Selenium's Chrome instance, but is actually intended as you configured a specific resolution instead of your browser window's size.

Alternative: Resizing browser window

As an alternative, you may ask your Selenium browser to resize:

page.driver.browser.manage.window.resize_to(1440, 990)

(On old Capybaras, you might need to use Capybara.current_session instead of page).

In case you want to maximize your browser window, use page.driver.browser.manage.window.maximize.

Keep in mind that the window size is limited by your display size and may be different for other developers; similarly, maximizing may result in different window sizes.


FYI: We've gotten reports that this also fixed obscure errors like unexpected '#' after 'DESCENDANT_SELECTOR' (Nokogiri::CSS::SyntaxError) for some.

Arne Hartherz
Last edit
Michael Leimstädtner
Keywords
startup, resize, maximize, firefox, chrome
License
Source code in this card is licensed under the MIT License.
Posted by Arne Hartherz to makandra dev (2012-07-10 10:50)