Automated Tests For Ruby With Watir

January 7th | By | Back to Blog

Watir, pronounced water, an abbreviation for Web-browser Automated Tests In Ruby, is an open-source family of Ruby libraries for automating web browsers. It allows you to write tests that are easy to read and maintain. It is simple and flexible.

Used by all the big names such as Facebook, Yahoo!, SAP, Oracle and more it drives browsers the same way people would do. It clicks links, fills in forms and presses buttons. Watir can also checks results, such as whether expected text appears on the page.

This post will only cover the basic of Watir without connecting it with a BDD framework such as Cucumber or RSpec.

1. Setting up a basic form

A pretty basic form would look like so:

<html>
<head>
	<meta http-equiv="Content-type" content="text/html; charset=utf-8">
	<title>index</title>
</head>
<body>
	<form action="index_submit" method="get" accept-charset="utf-8">
		<p><label for="inputtext">Please enter your name:</label><input type="text" name="text" value="" id="inputtext"></p>
		<p>What is your job title: <select name="some_name" id="some_name">
			<option value="option1">Developer</option>
			<option value="option2">Tester</option>
		</select></p>
		<p>What is your scripting language of choice? <label for="lang1">Python</label><input type="radio" name="lang" value="python" id=""><label for="lang1">Ruby</label><input type="radio" name="lang" value="ruby" id=""></p>
		
		<p><label for="checkbox">By checking this form you agree to submit your form</label><input type="checkbox" name="checkbox" value="1" id=""></p>
		<p>Free text: </p><textarea name="textarea" rows="8" cols="40" id="textarea"></textarea>
		<p><input type="file" name="file"></p>
		<p><label for="pass">Secret password: </label><input type="password" name="pass"></p>
		<p><input type="submit" value="Continue &rarr;"></p>
	</form>
</body>
</html>

2. Enter Watir

require 'watir-webdriver'
b = Watir::Browser.new
b.goto 'http://local.blogposts.com/testing-with-watir'
b.text_field(:name => 'text').set 'Guy'
b.select_list(:name => 'some_name').select 'Developer'
b.radio(:name => 'lang', :value => 'ruby').set
b.checkbox(:value => '1').set
b.text_field(:name => 'textarea').set "Web-driving with Watir!"
b.file_field(:id => 'file').set "/Users/egstudio/Downloads/file.jpeg"
b.text_field(:id => 'pass').set "1234"
b.button(:id, "submit").click

Run the script and enjoy the magic of Watir. In line one we require the watir webdriver gem, we then must create an instance of a browser. Afterwards we go to the form we created and fill in the data one by one and finally clicking submit.

Extra script:

Here’s an extra script if you would not like to create a form just to see how it works.

require ‘watir-webdriver’
b = Watir::Browser.new
b.goto ‘http://www.google.com’
b.text_field(:name => ‘q’).set ‘Watir’
b.button(:type => "submit", :name => ‘btnK’).click

Good luck!