Testing in Multiple Browser Windows with Watir and Watir-Webdriver

DevOps & Testing

August 2, 2012

There are many occasions, using Watir or Watir-Webdriver, when we need to do some testing in one browser window, open another, possibly close it, and return to the first. Watir handles this a bit more transparently than Watir-Webdriver.

With Watir you are dealing directly with IE through OLE and IE handles windows and tabs differently than Firefox and Chrome. Without getting into gory details, this means that you can, with Watir (and IE), have active references to multiple browser instances/windows at the same time. With Webdriver (using IE, Firefox, and Chrome) you have to switch between the windows explicitly before you can use them. Webdriver does this with all three because, in FF and Chrome, only one window is accessible at a time.

With Watir the following works fine:

browser = Watir::IE.new
browser.goto(an_initial_url)
browser.link(:text, 'Open This Window').click # opens a new window
popup = browser.attach(:url, /newwindow/)
popup.close
browser.link(:text, 'Open This Window').click # open it again

With Watir-webdriver the last click command fails so we do this:

browser = Watir::Browser.new(:firefox) # could be :chrome or :ie
browser.goto(an_initial_url)
browser.link(:text, 'Open This Window').click # opens a new window
browser.driver.switch_to.window(browser.driver.window_handles[0])
popup = browser.window(:url, /newwindow/).use
popup.close
browser.driver.switch_to.window(browser.driver.window_handles[0])
browser = browser.window(how, /#{uri_decoded_pattern}/).use
browser.link(:text, 'Open This Window').click # open it again

In the Awetest DSL we have encapsulated the variations for each browser and either Watir for IE or Watir-webdriver for IE, Firefox, or Chrome in the methods open_browser() and attach_browser().

This code then should work correctly in any Awetest script:

browser = open_browser(an_initial_url)
click(browser, :link, :text, 'Open This Window')
popup = attach_browser(browser, :url, popup_url)
# do things with the popup
# then reattach the original window
browser = attach_browser(browser, :url, an_initial_url)

While coming from different points of view, Watir and Watir-Webdriver (which uses Selenium Webdriver under the hood) are both powerful tools for browser testing.