Dashboard > Watir > ... > Start Here > FAQ
Watir Log In View a printable version of the current page.
FAQ
Added by Bret Pettichord, last edited by Alister Scott on Jun 20, 2008  (view change) show comment
Labels: 
(None)

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. There are tests for all of the features in Watir which can serve as excellent documentation and a basic tutorial.

See Watir Training Presentation and Exercises page.

How do I gem install Watir behind a proxy server?

Goto the cmd line
set HTTP_PROXY=http://mycache:8080

gem install watir

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?

See Internet Explorer Developer Toolbar page.

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

See Frames page.

How do I use regular expressions for object recognition?

See Regular Expressions page.

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

See Multiple Attributes page.

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 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 - the wait_until method.

An example might be that you're loading the Google home page and for some reason it's taking time to load. Here's a basic contrived script with a sleep statement.

require 'watir' 

browser = Watir::IE.start('http://www.google.com')
sleep 5     # we need to wait for the page to load and on a subjective basis I've chosen 5 seconds which works on my machine
browser.text_field(:name, 'q').set('ruby poignant')
....

Unfortunately the sleep is hardcoded and doesn't work for anyone else on my team who have slower network connections, my connection has gotten faster, but it still waits for 5 seconds before setting the text field.

Watir 1.5.x has added a wait_until method that can poll for a certain condition to return true before continuing on or erroring out. By default it checks the condition every half second up until 60 seconds. So I rewrite my code to look like this:

require 'watir' 
include Watir

browser = Watir::IE.start('http://www.google.com')
wait_until{ browser.text_field(:name, 'q').exists? }    # in this case all I care about is the text field existing, you could check title, text, anything you're 
                                                        # expecting before continuing
browser.text_field(:name, 'q')set('ruby poignant')
...

It now works for me with a half second delay, but also works for the other members of my team who have network delays up to a minute. If you're considering using sleep, use wait_until instead. It will make your test code more resilient to timing issues in those cases where you really need to use it.

How do I attach to a pop up window?

See Pop Ups page.

How do I access a security alert window?

See Security Alerts page.

How do I hide the browser window without using the -b flag?

See Tips and Tricks 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 JavaScript Pop Ups page.

How do I trigger JavaScript events?

See JavaScript page.

How do I interact with a JavaScript tree view?

See JavaScript page.

How do I handle asynchronous javascript / AJAX?

if you include asynchronous JS in your definition of done, you'll need to code around that specifically. There's an open feature request to have Watir's wait method track XHRs and timers that are launched when the page is loaded, and wait for them as well. That may be tricky to do though, and with an all-volunteer project, it really depends on someone making the time to do it.

In lieu of that, one option is having the application keep track if XHRs and timers that it kicks off, and setting the some value to true when they are all complete. For example:

def wait_until_loaded(timeout = 30)
    start_time = Time.now
    until (however_your_application_reports_its_loaded == 'true')  do
      sleep 0.1
      if Time.now - start_time > timeout
        raise RuntimeError, "Timed out after #{timeout} seconds"
      end
    end
  end

A simpler option is:

tries = 0
until browser.link(:text, /link_to_wait_for/).exists? do
  sleep 0.5
  tries += 1
end
browser.link(:text, /link_to_wait_for/).cick  
end

Another option is to retry until timeout or no exception is raised.

def rescue_wait_retry(exception = Watir::Exception::UnknownObjectException, times = 10, seconds = 2, &block)
  begin
    return yield
  rescue exception => e
    puts "Caught #{exception}: #{e}. Sleeping #{seconds} seconds." if $DEBUG
    sleep(seconds)
    @ie.wait
    if (times -= 1) > 0
      puts "Retrying... #{times} times left" if $DEBUG
      retry             
    end
  end
  yield
end

@ie.link(:url, %r|confirmdelete\.action\?educationId|).click #This starts some ajax stuff
rescue_wait_retry { @ie.button(:id, 'form_0').click }

Running Tests

Why are my test cases running in the wrong order?

See 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.

How do I use Excel with Watir for data-driven tests?

See Data-Driven Tests page.

How do I use OpenOffice.org Calc with Watir for data-driven tests?

See Data-Driven Tests page.

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

Try one of these:

  • Change your ruby permissions to "run as administrator"; or
  • Disable User Access Control; or
  • Turn off Internet Explorer Protected Mode

Ruby & Watir

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

See Tips and Tricks page.

How do I install a gem from the latest development source?

Note: If you've installed Watir with the One Click Installer. You should uninstall that version before attempting to upgrade to the development source gem.

Note: It is easier to simply use a recent development gem.

Projects on OpenQA use Subversion as the Source Code Management tool. TortoiseSVN is a good Subversion client which integrates into windows explorer.

Once TortoiseSVN is installed, checkout the source:

  • Create a folder to checkout into, this will be the watir_install_dir
  • Right click on watir_install_dir, from the context menu select SVN Checkout...
  • In the dialog box enter http://svn.openqa.org/svn/watir/trunk/watir for the url
  • Hit Ok, Watir source should now download into the watir_install_dir

Now that you have your own local copy of the source, you can create your own gem and install it into your local ruby gems directory. Open a command line, navigate to watir_install_dir and type the following:

gem build watir.gemspec

This will create a file that is named something like watir.1.5.1.1032.gem. The actual version number will be based on the latest revision number of the source in subversion.

 You can install your gem simply by typing this in the same directory:

gem install watir

Note that this command will first look for a watir gem in the current directory. If it isn't found there, then it will look to the gem server on the internet (at rubyforge.org).

This command will list the gem versions on your local system, you should now have the latest development version listed. 

gem list --local

You can also do a gem uninstall on previous versions if you'd like.

gem uninstall watir

and you'll get a list of versions to choose from.

To keep in sync with the latest code you can now right click on watir_install_dir, click on SVN Update and follow the gem install process again.

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 to create a Jira Ticket?

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

class Cookie
    def kill (dir= \
                  "C:\\Documents and Settings\\"+ENV['USERNAME']+"\\Local Settings\\Temporary Internet Files")
    require 'fileutils' 
    FileUtils.rm_rf dir
   end
 end

Martin wrote:

"If I register with this site, how can I prevent my email address from being indexed by Google?"
and
"How can I remove my details from the user database"

Martin - please contact the administrator of this site to have your information removed (I have also sent him an e-mail). The e-mail link is at the bottom of the page.

Site running on a free Atlassian Confluence Community License granted to OpenQA. Evaluate Confluence today.
Powered by Atlassian Confluence, the Enterprise Wiki. (Version: 2.5.6 Build:#812 Aug 06, 2007) - Bug/feature request - Contact Administrators