Unit testing in Watir

Watir is an open-source Ruby library for automating web browsers. Combined with unit testing for Ruby it is a really powerful tool to test websites and webapplications. In this post I explain how to write a test for a simple website.

Watir
Watir

First download and install Ruby. If you are familiar with Eclipse, Aptana is a nice web development plugin (see this simple installation tutorial). If you don’t know how to use Ruby, Bas has a nice article about getting started with Ruby.

The second step is install Watir. You can try these examples to see what Watir does.

Testing a simple website

For one of my school projects I had to write a simple test for one of the function of this online calculator. In this tutorial we will test the GCF and LCM function. Start with creating a new Ruby script containing the right requirements and a test case class:

In order to let Watir start a new browser add the following to the test_lcm_gcd function:

If you want to use Firefox for testing, change “ie” to “firefox” and don’t forget to install the plugin. The second line starts a new browser window.

Our goal is to let Watir insert two values (the ‘First Value’ and ‘Second Value’ input field), and then press the ‘Solve’ button. In order to do so we need to know the name or id (or value in some cases) of the input fields and the ‘Solve’ button. Instead of looking at the source I can recommend to use the Firebug add-on for Firefox, and use the inspect function. The ‘First Value’ input is named ‘a’, and the ‘Second Value’ input is named ‘b’. We want to set ‘a’ to 30 and ‘b’ to 45:

When these values are set, Watir must press the ‘Solve’ button. It appears this button doesn’t have a name or id, so get it by value and execute the click action:

Now the click action is executed and the result is printed in the other two input fields (named ‘lcmA’ and ‘gcdA’). Like in all other test cases, the result must be verified. The correct result is LCM = 90 and GCF = 15, so use assertions to check the values:

This simple test case is now complete. The test output should be something like this:

One thought on “Unit testing in Watir

  1. Not very helpful to be honest.

    i tried it but end up with the following errors:
    undefined method `assert’ for TC_LCM_GCD:Class (NoMethodError)

Leave a Reply

Your email address will not be published. Required fields are marked *