HOWTO use HtmlUnit with Ruby Watir

Is it possible to use HtmlUnit with Watir? Yes. HtmlUnit is a Java-based headless browser. Whilst it’s not possible to use it directly from (MRI) Ruby, it can be used with Selenium WebDriver and Watir via Selenium Server and Selenium WebDriver’s remote driver.


Running Selenium Server

Firstly you need to install Selenium Server, which includes HtmlUnit.

(Simply brew install selenium-server-standalone if you use Homebrew.)

Then run the following command:

selenium-server -port 4444

Selenium Server should then start running on port 4444.

Using HtmlUnit with Selenium WebDriver

Once you have Selenium Server running, you can connect with the following Ruby code:

require 'selenium-webdriver'

driver = Selenium::WebDriver.for :remote, {
  :url => 'http://localhost:4444/wd/hub',
  :desired_capabilities => :htmlunitwithjs
}

If you get a Selenium::WebDriver::Error::UnsupportedOperationError exception make sure you specify :htmlunitwithjs in the desired capabilities.

Using HtmlUnit with Watir

Watir is built on top of Selenium WebDriver, so using HtmlUnit with Watir is just a different require and an extra statement to wrap the driver:

require 'watir'

driver = Selenium::WebDriver.for :remote, {
  :url => 'http://localhost:4444/wd/hub',
  :desired_capabilities => :htmlunitwithjs
}

browser = Watir::Browser.new(driver)

You can then use the Watir API as you would with any other driver.