Skip to content
This repository has been archived by the owner on Jun 6, 2018. It is now read-only.
Justin Ko edited this page Jun 29, 2013 · 4 revisions

Getting Started

How do I use Watir?

A good place to start is typically the Watir Documentation Page which links you to the Quick Start Guide, the rdoc (api), articles, and other resources.

Anther good way to understand how to use Watir and get examples is to take a look at the unit tests in Watirspec. There are tests for all of the features in Watir, which can serve as excellent documentation and a basic tutorial.

How do I gem install Watir behind a proxy server?

Best approach:

http://justinram.wordpress.com/2006/02/27/installing-watir-via-the-gem-utility/

Goto the cmd line

set HTTP_PROXY=[http://mycache:8080](http://mycache:8080)
gem install watir

Explained in more detail here.

How do I require all ruby files in the current directory?

dir = File.dirname(__FILE__)
Dir[File.expand_path("#{dir}/*.rb")].uniq.each do |file|
  require file
end

Can I use Watir with Linux, Mac, Safari, Firefox?

Take a look at Platforms page of Watir web site.

Page Elements

How do I identify the attributes of HTML elements on my page?

There are toolbars you can use in Internet Explorer and Firefox. See Browser Development Toolbar for instructions.

Why do I get an access denied error when trying to access a frame?

See the Frames page.

How do I use regular expressions for object recognition?

Watir allows the tester to use Regular Expressions for object recognition instead of using the full string literal. This is useful for HTML objects that are dynamically created.

For example in my WebSphere application we may have a link with this URL

 $ie.link(:url, "javascript:PC_7_0_G7_selectTerritory('0',%20'amend')").click

However this: 'PC_7_0_G7_' will change dependent on the environment.

With RegEx we could find that link by doing :

 $ie.link(:url, /selectTerritory\('0',%20'amend'\)/).click

or this

 $ie.link(:url, /javascript.*selectTerritory\('0',%20'amend'\)/).click

note: '.*' will match any character or digit any number of times.

RegEx contains special characters that need to be escaped. For example here ')' we use the backward slash to escape a closing bracket.

To find out what characters need to be escaped, go into irb, then enter

Regexp.escape "javascript:PC_7_0_G7_selectTerritory('0',%20'amend')"

the escape sequences will be returned

=> "javascript:PC_7_0_G7_selectTerritory\\('0',%20'amend'\\)"

note: use only one backslash; we are shown two, because they are escaped within a string,

I have more than one object of the same name. How do I commit an action on anything but the first one?

Lets imagine we have two 'Employees' links. This will click the first link that is found on the page:

$ie.link(:text, 'Employees').click

Use this syntax for the second (or more):

$ie.link(:text => 'Employees', :index  => 1).click

Note that :index is 0-based (ie the first element is index 0).

How do I create an application/object map?

Insert the object recognition into a small method

def login_link; $ie.link(:text, 'Log in'); end
def username_field; $ie.text_field(:name, 'userid'); end

then in your test class do:

login_link.click
username_field.set(username)

Why does my code work in IRB but not in my .rb script?

See the Using IRB page.

How do I access Any Tag in HTML (DOM) with Watir?

Using Watir 1.5.6 or later, it is easy to extend Watir to support additional tags. Thus:

module Watir
  class Abbr < NonControlElement
    TAG = 'ABBR'
  end
end

This article from Bret about how to create your own classes that access HTML elements on the page using the Container Module using previous versions of Watir.

http://www.io.com/~wazmo/blog/archives/2006_10.html#000242

How do I deal with timing issues and not use sleep?

Sometimes you need to wait for something to happen in the Application under test before you interact with it. Sleep statements are hardcoded and lock you down into a certain number of seconds before moving through your test. To avoid that, we've written a polling mechanism in the latest versions of Watir - see the Waiting page.

How do I attach to a pop up window?

See the Browser Popups page.

How do I open multiple IE windows in separate processes?

As of development build 1.5.1.1100 a new IE.new_process method was added to 'watir/contrib/ie-new-process'. This starts up a new IE process for each IE window, which is really how it should be done. To close these use IE#kill. Any one getting intermittent RPC errors when opening windows may want to use this instead.

The following Example uses this method to create 5 IE process and add them to an array:

require 'watir/contrib/ie-new-process'
ies = []
5.times do
  ie = Watir::IE.new_process
  ies<<ie
end

How do I close all open IE windows?

This routine can be useful as part of setup or teardown. It attaches to, and closes, all open IE windows.

def close_all_windows
  loop do
    begin
      Watir::IE.attach(:title, //).close
    rescue Watir::Exception::NoMatchingWindowFoundException
      break
    rescue
      retry
    end
  end
end

An enhanced version of this functionality is now included in Watir 1.5. (It also closes modal web dialogs.)

require 'watir/close_all'
Watir::IE.close_all

A final brute-force method (that works on Windows XP) might be to kill all iexplore.exe processes via a system command:

system("taskkill /t /f /im iexplore.exe")

When IE throws up a JavaScript pop-up window, it appears to hang my Ruby script. How can I make those windows go away?

See the JavaScript Dialogs page.

How do I trigger JavaScript events?

If the tag contains a JavaScript call, you can use the "fire_event" method to trigger it. ex. onchange=doThis() or onmouseup=clearForm()

To trigger a text field named "my_field" with an onchange event we would do this with Watir:

ie.text_field(:name, "my_field").fire_event("onchange")

How do I handle asynchronous javascript / AJAX?

See the Waiting page.

Running Tests

Why are my Test-Unit test cases running in the wrong order?

See the Test Unit page.

How do I generate XML reports from my test case results?

If your tests inherit from TestCase or RSpec, take a look at Nick Sieger's project ci_reporter which can run from a Rakefile and collect your results in xml that can be picked up by projects that understand xunit xml reports, such as Cruise Control. Cruise Control is a great continuous integration server with versions for Ruby, Java and .Net and can provide a nice dashboard and runner for your tests.

Here's an extremely simple example using test::unit and ci_reporter. For more examples refer to the information for ci_reporter on Nick's site.

Example:

require 'test/unit'
require 'ci/reporter/rake/test_unit_loader.rb'
require 'watir'

class My_Test < Test::Unit::TestCase

  def test_me
    browser = Watir::IE.start('http://www.google.com')
    assert(browser.link(:text, 'About Google').exists?)
    browser.close
  end

end

Note: Report files are written, by default, to the test/reports or spec/reports subdirectory of your project. If you wish to customize the location, simply set the environment variable CI_REPORTS (either in the environment, on the Rake command line, or in your Rakefile) to the location where they should go.

What should I do if two browser windows appear when running a test under Windows Vista?

Try one of these:

  • Add your default homepage (or 'About:Blank' if you start with a blank page) to the same security group (e.g. 'intranet' or 'trusted sites') as the site you are testing; or
  • Turn off Internet Explorer Protected Mode; or
  • Change your ruby permissions to "run as administrator"; or
  • Disable User Access Control

Ruby & Watir

How do I get the version numbers of Ruby and Watir?

Go to command prompt.

For the Watir version type:

gem list watir

For the Ruby version type:

ruby -v

How do I search the mailing list archives?

Visit Watir Search, Google custom search engine that searches Watir web sites, wiki, bug tracker, source and all Watir related mailing lists (and nothing else).

How do I take screenshots and append to a Word file?

require 'watir'
require 'win32ole'
@@word=WIN32OLE.new('Word.Application')
@@word.Documents.Add()

def take_a_screenshot(url)
  @autoit = WIN32OLE.new("AutoItX3.Control")
  browser = Watir::IE.new
  browser.bring_to_front
  browser.goto(url)
  browser.maximize
  @autoit.Send("{PRINTSCREEN}")
  browser.close
  @@word.Selection.Paste
  @autoit.Send("{ENTER}")
end

def save_file
  @@word.ActiveDocument.SaveAs('C:\screenshots.doc')
  @@word.ActiveDocument.close
  @@word.Quit
end

take_a_screenshot('http://www.agiletester.co.uk')
take_a_screenshot('http://www.fsf.org/')
save_file

How do I delete all cookies

require 'fileutils'
class Cookies
  def delete(dir= "C:\Documents and Settings\#{ENV['USERNAME']}\Cookies")
    # or wherever your cookies are downloaded to (can be browser specific)
    FileUtils.rm_rf dir
  end
end

How do I fix a WIN32OLERuntimeError when I use AutoIt?

In some cases, after you install Watir, the .dll file fails to get registered which gives an error similar to the following:

Exception 'WIN32OLERuntimeError' at <filename.rb>:<line#> - unknown OLE server: 'AutoItX3.Control'

If this is your problem, then all you need to do is type the following where your AutoItX3.dll file is installed (if you are using Watir's version of AutoIt then on windows for 1.5.6 it should be at: c:\ruby\lib\ruby\gems\1.8\gems\watir-1.5.6\watir, for 1.6.2 it should be at: C:\ruby\lib\ruby\gems\1.8\gems\watir-1.6.2\lib\watir )

regsvr32 AutoItX3.dll

Following this you will see a pop-up window saying: "DllRegisterServer in autoitx3.dll succeeded."