Monday, December 29, 2008

Getting started with Ruby and Watir

As a web developer, I'm always on the look out for ways to improve the quality of the web applications I develop.

One of the tools that I am trying out recently is Watir (pronounced Water). It's too early for me to say whether it's as good as or better than Selenium but I have to admit, learning ruby in the process is a nice bonus. Compared to my experience learning TCL, I found Ruby to be easier to learn.

Here's a quick run down of the steps to get started with installing Ruby and using Watir. Before anything else, I would recommend absolute newbies to try this on Windows first because it will be much easier and quicker.
  1. Download the Ruby one click installer
  2. Double click on the file you download and follow the instructions to install ruby
  3. Open a command prompt and type the following to update ruby and install watir
  4. gem update --system
    gem install watir

  5. We would also want to run tests on firefox, so let's install additional ruby packages that will allow us to do that
  6. gem install firewatir

  7. To allow firefox to work with Watir, you'll need to install the jssh plugin for firefox.
I wrote a script to check if IE and Firefox works with Watir. Copy the script below into a file mytest.rb and save it to your computer.
# set the variables
validator_site = "http://validator.w3.org"
url_to_check = "http://www.google.com"
browser = "ff"

if browser == "ie"
require "watir"
ctrl = Watir::IE.new
else
require "firewatir"
include FireWatir
ctrl = Firefox.new
end

puts "1. Open validator site"
ctrl.goto validator_site

puts "2. Type url to validate"
ctrl.text_field(:name,"uri").set url_to_check

puts "3. Submit the URL"
ctrl.link(:class,"submit").click

puts "4. Results ... "
if ctrl.text.include? "Errors found"
puts " Test FAILED."
else
puts " Test PASSED!"
end

ctrl.close

To execute the script, open a command prompt and type

ruby mysite.rb

To try it with Internet Explorer, change the browser variable from 'ff' to 'ie'.

The script simply loads up the w3c validator site and submit "http://www.google.com" for validation. The command prompt will output messages as the script progresses. In the end, it checks whether the words "Errors found" is on the page and outputs a Success or Fail depending on whether those words are found or not.

No comments:

Post a Comment