Thursday, December 8, 2011

Watir-WebDriver


WebDriver is a common browser automation tool that uses what ever is the most appropriate mechanism to control a browser, but with a common API. WebDriver supports not only real browsers (IE, Chrome & Firefox) but also headless ones (using HtmlUnit). It’s basically a nice Watir (ruby) implementation on WebDriver, so it gives you four browsers (three real, one headless) using one neat API, out of the box.

Running Watir-WebDriver

There are essentially two components you need: the Watir-WebDriver ruby gem, and the remote WebDriver server. The remote WebDriver server is only needed if you want to run your tests in headless mode without a real browser (or want to use Opera).

The Watir-WebDriver ruby gem

It’s a simple matter of opening a command prompt and typing:

gem install watir-webdriver (windows)

The remote WebDriver Server

This is the slightly tricky part. This is so that WebDriver can run headless without a real browser, and isn’t needed for real browser support (bar Opera). The quickest easiest way to get up and running is to download this java jar file, open a command prompt where you have saved it, and run:

java -jar selenium-server-standalone-2.0b1.jar

Example:

require 'rubygems'
require 'watir-webdriver'
b = Watir::Browser.new :chrome
b.goto 'www.google.com'
b.text_field(:name => 'q').set 'watir'
b.button(:name => 'btnK').click
b.div(:id => 'center_col').wait_until_present
puts "Displaying page: '#{b.title}' with results: '#{b.div(:id => "center_col").text}'"
b.close

The only difference for Firefox:

b = Watir::Browser.new :firefox

The only difference for IE:

b = Watir::Browser.new :ie

Watir 2.0.4


Watir 2.0.4 has been released. This version has the following changes:

* IE#execute_script escapes multi-line JavaScript scripts
* allow css and xpath locators for element collection methods, fixes
* Zero based Indexing

Install it with:
gem install watir