This will help you for Automation Software Testing with Watir Tool(Ruby)
Thursday, August 26, 2010
PPT
•Download the One-Click Ruby Installer for Windows (v.1.8.6-26) from the Ruby One Click Installer Page .
Saturday, July 3, 2010
Watir: Live Scripting Example: Live scripting example in watir
You can learn more.....
require 'watir'
require 'test/unit'
require 'script_runner'
include Watir
class YatraFlights < Test::Unit::TestCase
script_runner = ScriptRunner.new("C:","C:","Yatra_Flights","",4,4,false)
def test_01_Homepage
$ie = IE.new
$ie.goto("http://www.yatra.com/")
$ie.maximize()
$ie.bring_to_front()
$ie.maximize()
assert($ie.text_field(:name ,"ddate").exists?)
assert($ie.link(:text,"Hotels").exists?)
#~ assert($ie.contains_text("Book your Trip!"))
end
def test_02_Flight_Book_Page
$ie.maximize()
x=(Date.today+(25)).strftime('%d/%m/%Y')
y=(Date.today+(28)).strftime('%d/%m/%Y')
$ie.radio(:name,"type","O").set
$ie.selectBox( :name ,"origin").select("Bangalore")
$ie.selectBox( :name ,"destination").select("Mumbai")
$ie.text_field(:name,'ddate').value=x
$ie.button(:id,'flightsonlybtn').click
$ie.maximize()
$ie.bring_to_front()
$ie.maximize()
#~ assert($ie.image(:src,/selectDepart.gif/).exists?)
assert($ie.contains_text("Selection Summary"))
assert($ie.image(:src,/selectDepart.gif/).exists?)
end
def test_03_Flight_Booking_Results_Page
#~ $ie.image(:src,/selectDepart.gif/).click
$ie.image(:src,/selectDepart.gif/).click
sleep 5
assert($ie.contains_text("Total Travel Price"))
assert($ie.button(:value,/Continue/).exists?)
end
def test_04_Flight_Review_Page #Yatra Flight Passenger Page
#~ $ie.div(:id,'contBooking').button(:name,'submit').click
$ie.button(:value,/Continue/).click
#~ assert($ie.checkbox(:name,'ch1').exists?)
assert($ie.contains_text(/Review Details/))
assert($ie.contains_text(/Pricing Details/))
assert($ie.button(:alt,/Continue Booking/).exists?)
end
def test_05_Flight_Passenger_Page
$ie.radio(:name,/barclay_radio/).click
$ie.checkbox(:name,'ch1').set
$ie.checkbox(:name,'ch3').set
$ie.button(:alt,/Continue Booking/).click
assert($ie.text_field(:name,'contact_first_name').exists?)
assert($ie.text_field(:name,'password').exists?)
end
require 'watir'
require 'test/unit'
require 'script_runner'
include Watir
class YatraFlights < Test::Unit::TestCase
script_runner = ScriptRunner.new("C:","C:","Yatra_Flights","",4,4,false)
def test_01_Homepage
$ie = IE.new
$ie.goto("http://www.yatra.com/")
$ie.maximize()
$ie.bring_to_front()
$ie.maximize()
assert($ie.text_field(:name ,"ddate").exists?)
assert($ie.link(:text,"Hotels").exists?)
#~ assert($ie.contains_text("Book your Trip!"))
end
def test_02_Flight_Book_Page
$ie.maximize()
x=(Date.today+(25)).strftime('%d/%m/%Y')
y=(Date.today+(28)).strftime('%d/%m/%Y')
$ie.radio(:name,"type","O").set
$ie.selectBox( :name ,"origin").select("Bangalore")
$ie.selectBox( :name ,"destination").select("Mumbai")
$ie.text_field(:name,'ddate').value=x
$ie.button(:id,'flightsonlybtn').click
$ie.maximize()
$ie.bring_to_front()
$ie.maximize()
#~ assert($ie.image(:src,/selectDepart.gif/).exists?)
assert($ie.contains_text("Selection Summary"))
assert($ie.image(:src,/selectDepart.gif/).exists?)
end
def test_03_Flight_Booking_Results_Page
#~ $ie.image(:src,/selectDepart.gif/).click
$ie.image(:src,/selectDepart.gif/).click
sleep 5
assert($ie.contains_text("Total Travel Price"))
assert($ie.button(:value,/Continue/).exists?)
end
def test_04_Flight_Review_Page #Yatra Flight Passenger Page
#~ $ie.div(:id,'contBooking').button(:name,'submit').click
$ie.button(:value,/Continue/).click
#~ assert($ie.checkbox(:name,'ch1').exists?)
assert($ie.contains_text(/Review Details/))
assert($ie.contains_text(/Pricing Details/))
assert($ie.button(:alt,/Continue Booking/).exists?)
end
def test_05_Flight_Passenger_Page
$ie.radio(:name,/barclay_radio/).click
$ie.checkbox(:name,'ch1').set
$ie.checkbox(:name,'ch3').set
$ie.button(:alt,/Continue Booking/).click
assert($ie.text_field(:name,'contact_first_name').exists?)
assert($ie.text_field(:name,'password').exists?)
end
Wednesday, June 9, 2010
Watir: Watir Scripting
Ruby Database
equire 'win32ole'
class SqlServer
# This class manages database connection and queries
attr_accessor :connection, :data, :fields
attr_writer :username, :password
def initialize(sclient,script,pagecode,pagenum,host='', username='', password='',database='')
puts "in init"
#~ @dbtype=readINI("C:/config/DB.ini","DBtype")
@connection = nil
@@sclient=sclient
@@script=script
@@pagecode=pagecode
@@pagenum=pagenum
@data = nil
@timeout=60
@sclient2=sclient
puts "in init"
end
#end
def open()
# Open ADO connection to the SQL Server database
connection_string = "Provider=SQLOLEDB.1;"
connection_string << "Persist Security Info=False;"
connection_string << "User ID=#{$username};"
connection_string << "password=#{$password};"
connection_string << "Initial Catalog=#{$database};"
connection_string << "Data Source=#{$host};"
connection_string <<"Connect Timeout=#{@timeout};"
connection_string << "Network Library=dbmssocn"
puts connection_string
@connection = WIN32OLE.new('ADODB.Connection')
#~ if @dbtype="mssql"
@connection.Open(connection_string)
#~ else
#~ $dbh = Mysql.real_connect( @host,@username,@password ,@database)
#~ end
end
def query(sql)
# Create an instance of an ADO Recordset
recordset = WIN32OLE.new('ADODB.Recordset')
#puts @connection
# Open the recordset, using an SQL statement and the
# existing ADO connection
recordset.Open(sql, @connection)
# Create and populate an array of field names
@fields = []
recordset.Fields.each do |field|
@fields << field.Name
end
begin
# Move to the first record/row, if any exist
recordset.MoveFirst
# Grab all records
@data = recordset.GetRows
rescue
@data = []
end
#~ recordset.Close
# An ADO Recordset's GetRows method returns an array
# of columns, so we'll use the transpose method to
# convert it to an array of rows
@data = @data.transpose
end
def close
#~ recordset.Close
@connection.Close
end
end
equire 'win32ole'
class SqlServer
# This class manages database connection and queries
attr_accessor :connection, :data, :fields
attr_writer :username, :password
def initialize(sclient,script,pagecode,pagenum,host='', username='', password='',database='')
puts "in init"
#~ @dbtype=readINI("C:/config/DB.ini","DBtype")
@connection = nil
@@sclient=sclient
@@script=script
@@pagecode=pagecode
@@pagenum=pagenum
@data = nil
@timeout=60
@sclient2=sclient
puts "in init"
end
#end
def open()
# Open ADO connection to the SQL Server database
connection_string = "Provider=SQLOLEDB.1;"
connection_string << "Persist Security Info=False;"
connection_string << "User ID=#{$username};"
connection_string << "password=#{$password};"
connection_string << "Initial Catalog=#{$database};"
connection_string << "Data Source=#{$host};"
connection_string <<"Connect Timeout=#{@timeout};"
connection_string << "Network Library=dbmssocn"
puts connection_string
@connection = WIN32OLE.new('ADODB.Connection')
#~ if @dbtype="mssql"
@connection.Open(connection_string)
#~ else
#~ $dbh = Mysql.real_connect( @host,@username,@password ,@database)
#~ end
end
def query(sql)
# Create an instance of an ADO Recordset
recordset = WIN32OLE.new('ADODB.Recordset')
#puts @connection
# Open the recordset, using an SQL statement and the
# existing ADO connection
recordset.Open(sql, @connection)
# Create and populate an array of field names
@fields = []
recordset.Fields.each do |field|
@fields << field.Name
end
begin
# Move to the first record/row, if any exist
recordset.MoveFirst
# Grab all records
@data = recordset.GetRows
rescue
@data = []
end
#~ recordset.Close
# An ADO Recordset's GetRows method returns an array
# of columns, so we'll use the transpose method to
# convert it to an array of rows
@data = @data.transpose
end
def close
#~ recordset.Close
@connection.Close
end
end
Friday, April 9, 2010
Watir: Introduction: What is Watir
Introduction
"Watir" (pronounced water) stands for "Web Application Testing in Ruby". Watir is an automated test tool which uses the Ruby scripting language to drive the Internet Explorer web browser. Watir is a toolkit for automated tests to be developed and run against a web browser.What Does Watir Work With?
Watir will drive web applications that are served up as HTML pages in a web browser. Watir will not work with ActiveX plugin components, Java Applets, Macromedia Flash, or other plugin applications. To determine whether Watir can be used to automate a part of a web application, right click on the object and see if the View Source menu option is available. If you can view the HTML source, that object can be automated using Watir.Prerequisites
To use the tool, you should have a basic understanding of:- HTML: This is a basic HTML tutorial.
- Programming: You should understand programming basics, including variables and simple control structures like "for" loops and "if" statements.
- Ruby: You do not need to know how to program in Ruby to get started with Watir, but you should learn some Ruby if you really want to get the most out of Watir
- Check out the Ruby Cheat Sheet for basic Ruby information.
- Microsoft has a toolbar for Internet Explorer which can be useful in navigating the DOM for pages that you're looking to automate.
Watir: Install Ruby: How to Installed Ruby ?
- Log in as administrator.
- Download the One-Click Ruby Installer for Windows (v.1.8.6-26) from the Ruby One Click Installer Page .
We recommend using the latest version of Ruby 1.8.6 with Watir 1.6.
Watir's modal dialog support in Watir 1.5 required Ruby 1.8.2. This is no longer true and this feature now requires Ruby 1.8.6. - Run it (leave all choices at the default).
- You have installed Ruby.
- Installing Ruby 1.9.1
Install the lastest 1.9.1 RubyInstaller and development kit from here: http://rubyforge.org/frs/?group_id=167
(at the time of writing it is this: rubyinstaller-1.9.1-p243-rc1.exe)
Note: The Ruby path is not set by default but there is an option to set it in the installer
Type ruby -v in the command line which should return
ruby 1.9.1p243 (2009-07-16 revision 24175) [i386-mingw32]
You can have >1 versions of Ruby installed, but the first that is found in the path is used.
Download 7-zip www.7-zip.org and unzip the devkit to here C:\ruby19
Watir: Install Watir: How to install Watir?
nstalling from behind a proxy
If you are installing from behind a proxy, be sure to add the following to the end of any gem install or gem update command:
For example, if your proxy server was named proxy and it accepted connections on port 8000, your addition to the command line would be
Read the gem install documentation for more information on specifying the proxy.
Watir's support for Firefox also requires a plugin.
FireWatir Installation#InstalltheJSSHFirefoxExtension
http://intertwingly.net/blog/2008/11/23/RubyGems-1-3-1-on-Ubuntu-8-10
Type these commands at a command prompt:
Watir's support for Firefox also requires a plugin.
FireWatir Installation#InstalltheJSSHFirefoxExtension
If you are installing from behind a proxy, be sure to add the following to the end of any gem install or gem update command:
-p http://your-proxy-server-name:your-proxy-server-port
-p http://proxy:8000
Windows
Watir supports Internet Explorer 5.5, 6 and 7 on Windows 2000, XP, Server 2003 and Vista. Watir also supports Firefox 2 and 3.- Make sure you are logged in as administrator.
- Open command prompt and type:
gem update --system gem install watir
- Beginning with Watir 1.6.0 (Oct 2008), this installs drivers for both
IE and Firefox (FireWatir). Output should be something like this:
C:\Documents and Settings\Administrator\>gem install watir Successfully installed watir-1.5.x Installing ri documentation for watir-1.5.x... Installing RDoc documentation for watir-1.5.x...
- Watir's support for Firefox also requires a plugin.
FireWatir Installation#InstalltheJSSHFirefoxExtension
Mac
Type these commands at a command prompt:sudo gem update --system sudo gem install firewatir sudo gem install safariwatir
FireWatir Installation#InstalltheJSSHFirefoxExtension
Linux
To solve Ubuntu 8.10 gem hassle:http://intertwingly.net/blog/2008/11/23/RubyGems-1-3-1-on-Ubuntu-8-10
Type these commands at a command prompt:
sudo gem update --system sudo gem install firewatir
FireWatir Installation#InstalltheJSSHFirefoxExtension
When you install Watir, you may get an error building the documentation for the Builder gem. You can safely ignore this error. |
watir:Run Unit Tests:How to run Unit test in Watir?
The unit tests don't work with the Watir 1.6 gem, as described below. Sorry.
You will need a development environment (Get the source code and unit tests from SVN) to run them.
Unit Tests
If you are following the Quick Start Guide, this section is not necessary to get up and running
To run the unit tests:
And press "F5"
You will need a development environment (Get the source code and unit tests from SVN) to run them.
Unit Tests
If you are following the Quick Start Guide, this section is not necessary to get up and running
Running the Unit Tests
After you have installed Ruby and Watir, you can run the unit tests to verify the installation.To run the unit tests:
- If you have installed Ruby in its default folder of "C:\Ruby" then in "SciTE" goto:
C:\ruby\lib\ruby\gems\1.8\gems\watir-1.5.x\unittests\core_tests.rb
- The tests should all run and pass.
- If you receive any errors, try updating your gems with:
gem update
Having Problems?
If you are using Windows XP with Service Pack 2 or Windows Server 2003, several tests will fail unless you enable active content. To fix this:- From the browser, select Tools > Internet Options
- Select the Advanced tab
- Under Security, check Allow active content to run in files on My Computer
- Click OK
Additional Problems
- If you have the google toolbar installed, you will need to turn off the popup blocker.
- If you are installing on a new system, you will get a dialog asking about auto-complete. You will have to answer this question before you can run the unit tests.
- The following gems must be installed. (These are installed when you install the watir gem.)
- activesupport
- user-choices
Install Browser Developer Toolbar
To view details of elements in your web application, it is recommended to use a developer toolbar as it will provide element inspection functionality. These quickly show you the element attributes and properties you need to know to automate them with Watir.
There are two recommended packages depending on whether you prefer Internet Explorer or Firefox.
There are two recommended packages depending on whether you prefer Internet Explorer or Firefox.
Browser | Developer Toolbar |
---|---|
Internet Explorer | IE Developer Toolbar |
Firefox | Firebug |
Ruby Cheat Sheet
This cheat sheet describes Ruby features. It's not a reference to the language. You do have a reference to the language: the full text of Programming Ruby: The Pragmatic Programmer's Guide is installed with Ruby. Select start -> All Programs -> Ruby -> Ruby Documentation -> RubyBook Help.
Now the variable number has the value 5. Ordinary variables begin with lowercase letters. After the first character, they can contain any alphabetical or numeric character. Underscores are helpful for making them readable:
A variable's value is gotten simply by using the name of the variable. The following has the value 10:
Strings are objects in Ruby. This means that they have methods. (In fact everything in Ruby is an object.)
A method call looks like this:
A method is a function for a particular type of object. In this case, the thing before the period is the object, in this case a string simon. The method is upcase. It capitalizes its object.
Like functions, methods can have arguments.
This method is true if its argument book is a substring of bookkeeper.
You can also concatenate strings using the + operator.
Put the if, else, and end on separate lines as shown. You don't have to indent, but you should.
Functions can return values, and those values can be assigned to variables. The return value is the last statement in the definition. Here's a simple example:
Note that we didn't need to say five(), as is required in some languages. You can put in the parentheses if you prefer.
The value of the last statement is always the value returned by the function. Some people like to include a return statement to make this clear, but it doesn't change how the function works. This does the same thing:
Here's a little more complicated example:
To use it in another script, we must require it:
This will cause Ruby to search its loadpath for a file named mathplus.rb. (It will automatically add the .rb.) It will search the directories that normally contain Ruby libraries, as well as the current directory (typically the same directory as your script).
If your library is in a location that Ruby doesn't know about, you will need to change the loadpath:
Make sure you include this line before you require libraries in it.
This is an array with two numbers in it:
This is an array with two numbers and a string in it. You can put anything into an array.
Here's how you get something out of an array:
Here's how you get the last element out:
Here's another way to get the last element:
Here's how you change an element:
How long is an array?
Here's how you tack something onto the end of an array:
Here's one way to print the numbers from one to 10:
And here's another:
The part between the do and the end is called a block. You can replace the do and end with braces:
The 1..10 is a range, which works like an array of the numbers from 1 to 10. The each is a method that iterates through each element of the range. It is called an iterator.
This prints each value of an array:
What if you want to transform each element of an array? The following capitalizes each element of an array.
Regular expressions are characters surrounded by // or %r{}. A regular expression is compared to a string like this:
Most characters in a regular expression match the same character in a string. So, these all match:
This also matches:
Notice that the regular expression can match anywhere in the string. If you want it to match only the beginning of the string, start it with a caret:
If you want it to match at the end, end with a dollar sign:
If you want the regular expression to match any character in a string, use a period:
There are a number of other special characters that let you amazing and wonderful things with strings. Ruby uses the standard syntax for regular expressions used in many scripting languages. See Programming Ruby for more information about regular expressions.
What happens if there's no match? Type this:
and the result will be nil, signifying no match. You can use these results in an if, like this:
In Ruby, anything but the two special values false and nil are considered true for purposes of an if statement. So match results like 0 and 10 count as true.
Here's how to search an array for an element:
The detect method takes a block as an argument. This block returns true if the first argument starts with an r. (Actually it returns 0, which counts as true.) The detect method itself returns the first element for which its block is true.
When blocks are longer than one line, they are usually written using do and end. This is another way of writing the same code:
Here's how you create a dictionary:
Here's how you associate a value with a key:
Here's how you retrieve a value, given a key:
Here's how you ask how many key/value pairs are in the dictionary:
What values does a dictionary have?
What keys does it have?
You can do this
And this:
Comments
In Ruby, any text on a single line that follows a # is a comment, and is ignored by the Ruby interpreter at run time.# comment
Function Calls
Parentheses can sometimes be omitted. If you're not sure whether they're required, put them in. To be safe, put them in whenever the call is at all complicated. Even one as simple as this.puts "hello" puts("hello") assert_equal(5, number)
Variables
Ordinary (local) variables are created through assignment:number = 5
this_is_my_variable = 5
number + this_is_my_variable # returns 10
Strings, Objects and Methods
Strings are sequences of text in quotation marks. You can use single or double quotes.name = 'simon' name = "simon"
A method call looks like this:
"simon".upcase # returns "SIMON"
Like functions, methods can have arguments.
"bookkeeper".include?('book') # returns true
You can also concatenate strings using the + operator.
"dog" + "house" # returns "doghouse"
Conditionals (if)
if number == 5 puts "Success" # "Success" is a string. Strings can be surrounded with single or double quotes. else puts "FAILURE" end
Function Definitions
def assert_equal(expected, actual) if expected != actual puts "FAILURE!" end end
def five # note that no parentheses are required 5 end box = five # box's value is 5
The value of the last statement is always the value returned by the function. Some people like to include a return statement to make this clear, but it doesn't change how the function works. This does the same thing:
def five return 5 end
def make_positive(number) if number < 0 -number else number end end variable = make_positive(-5) # variable's value is 5 variable = make_positive(five) # variable's value is 5
Libraries
Libraries contain functions or methods that can be used in many Ruby programs. Suppose we store the make_positive function defined above in a file called mathplus.rb.To use it in another script, we must require it:
require 'mathplus'
If your library is in a location that Ruby doesn't know about, you will need to change the loadpath:
$LOAD_PATH << 'c:/my_lib/'
Arrays
This is an array with nothing in it:[]
[1, 2]
[1, 'hello!', 220]
array = [1, 'hello', 220] array[0] # value is 1
array[2] # value is 220
array.last # value is 220
array[0]= 'boo!' # value printed is 'boo!' # array is now ['boo', 'hello', 220]
array.length # value is 3
array.push('fred') # array is now ['boo', 'hello', 220, 'fred']
Iteration
When you do something multiple times, it is called iteration. There are many ways to do this. The following will print hello five times:5.times do puts 'hello' end
for x in 1..10 do puts x end
(1..10).each do |x| puts x end
(1..10).each { |x| puts x }
This prints each value of an array:
["a", "b", "c"].each { |x| puts x }
["hi", "there"].collect { |word| word.capitalize } # The result is ["Hi", "There"].
Regular Expressions
Regular expressions are a useful feature common to many languages. They allow you to match patterns in strings.Regular expressions are characters surrounded by // or %r{}. A regular expression is compared to a string like this:
regexp =~ string
/a/ =~ 'a string' /a/ =~ 'string me along'
/as/ =~ 'a string with astounding length'
/^as/ =~ 'alas, no match'
/no$/ =~ 'no match, alas'
/^.s/ =~ "As if I didn't know better!"
Truth and Falsehood
If you try the examples above, you'll see that the ones that match print a number. That's the position of the first character in the match. The first expression (/a/ =~ 'a string') returns 0. (Ruby, like most programming languages, starts counting with 0.) The second returns 10.What happens if there's no match? Type this:
/^as/ =~ 'alas, no match'
if /^as/ =~ some_string puts 'the string begins with "as".' end
Blocks
A block is like a function without a name. It contains a set of parameters and one or more lines of code. Blocks are used a lot in Ruby. Iterators like each use blocks.Here's how to search an array for an element:
gems = ['emerald', 'pearl', 'ruby'] gems.detect { |gem| /^r/ =~ gem } # returns "ruby"
When blocks are longer than one line, they are usually written using do and end. This is another way of writing the same code:
gems.detect do |gem| /^r/ =~ gem end
Dictionaries
A dictionary lets you say "Give me the value corresponding to key." Dictionaries are also called hashes or associative arrays.Here's how you create a dictionary:
dict = {}
dict['bret'] = 'texas' # looks a lot like an array, except that the key doesn't have to be a number.
dict['bret'] # value is 'texas'.
dict.length # value is 1
dict.values # value is the Array ['texas'].
dict.keys # value is the Array ['bret'].
Expression Substitution
Expression substitution evaluates an expression within a string:You can do this
name = "Aidy" puts "My name is: #{name}" => My name is: Aidy
puts "The sum of four times four is: #{4*4}" => The sum of four times four is: 16
Example Test Case
Google Test Search
This document walks through a very simple test case:. To begin, open it in a text editor. If you do not have that file, download it from . To open it with SciTE, simply right-click the file in Windows Explorer, and select Edit from the popup menu.The format of this example will be to show the Ruby test case scripting code in a box as you would see it in a text editor, with an explanation after it.
Getting Started
Open Internet Explorer, and try out the test case manually on your own:- go to the Google home page
- enter pickaxe in the search text field
- click the Google Search button
Expected Result
A Google page with results should be shown. Programming Ruby should be high on the list.Once you have tried the test case out manually, it's time to automate the test case using Watir. Return to the Google home page and view the page source: right mouse click > View Source. Now you can follow along and see how to automate this test with Watir based on the HTML tags in the Google search web application.
Section 1: Comments
Test cases should be commented, just as program code should be commented. In Ruby, any text on a single line that follows a # is a comment, and is ignored by the Ruby interpreter at run time.What you see in the text editor:
#-------------------------------------------------------------# # Demo test for the Watir controller. # # Simple Google test written by Jonathan Kohl 10/10/04. # Purpose: to demonstrate the following Watir functionality: # * entering text into a text field, # * clicking a button, # * checking to see if a page contains text. # Test will search Google for the "pickaxe" Ruby book. #-------------------------------------------------------------#
Section 2: Includes
To use Watir, or any other library in our test case, requires us to tell the program where to find the library.What you see in the text editor:
# the Watir controller require "watir"
Section 3: Declare Variables
If we are going to use something in our script more than once, or something that could change, we can declare it as a variable and reuse it throughout the script. Some objects we can use for testing tend to change, such as URLs for applications we are testing. In this script, we assign the test URL as a variable. If it changes, we only have to change it in one place.What you see in the text editor:
# set a variable test_site = "http://www.google.com"
Section 4: Open an Internet Explorer Browser
To begin driving Internet Explorer, we need to tell Watir to open an instance for testing.What you see in the text editor:
# open the IE browser ie = Watir::IE.new
Section 5: Interacting With Google
Now we are ready to start automating the steps we ran manually using Watir.Beginning the test case
What you see in the text editor:# print some comments puts "Beginning of test: Google search."
Step 1: Go to the Google site
This test case follows a pattern of printing out what we intend Watir to do on a web application, followed by the Watir scripting code to carry out that action. This is a style of test case development that is useful for tracking down test case failures quickly.What you see in the text editor:
puts " Step 1: go to the test site: " + test_site ie.goto test_site
Step 2: Enter Search Term pickaxe in the search field
We need to enter the term to search in the text field on the Google home page.What you see in the web browser:
puts " Step 2: enter 'pickaxe' in the search text field." ie.text_field(:name, "q").set "pickaxe" # "q" is the name of the search field
This is the tag in the HTML source with the name attribute we used:
"Google Search" value="">
Step 3: Click the Google Search button
We need to click the search button to activate the Google Search functionality.What you see in the web browser:
puts " Step 3: click the 'Google Search' button." ie.button(:name, "btnG").click # "btnG" is the name of the Search button
This is the tag in the HTML source with the name attribute we used:
"Google Search">
Section 6: Evaluating the Results
The Expected Result
This test case prints out what the Expected Result should be prior to the test case using Watir to evaluate the results.What you see in the text editor:
puts " Expected Result:" puts " A Google page with results should be shown. 'Programming Ruby' should be high on the list."
Verify Results
Using Watir and a little Ruby, we can evaluate the results to verify whether the test case passed or failed.puts " Actual Result:" if ie.text.include? "Programming Ruby" puts " Test Passed. Found the test string: 'Programming Ruby'. Actual Results match Expected Results." else puts " Test Failed! Could not find: 'Programming Ruby'." end
- The first line prints out the Actual Result heading to the screen.
- The second line gets the text of the page and then calls the include? method to determine whether Programming Ruby appears on the first page.
- Using an if statement, we evaluate whether the include? method was true or false.
- If include? returns true (or actually anything but false), the text Programming Ruby appears. The test case passes and we print the Test Passed. message.
- Else, if include? returns false, the text Programming Ruby does not appear. The test case fails and we print the Test Failed! message.
- We close the conditional if section with an end statement.
End of Test Case
What you see in the text editor:puts "End of test: Google search."
Developing Test Cases
The goal of this user guide is to help you get started writing test cases quickly. Each section describes the methods for driving a web application. Select the ones you need for each page of your web application based on the content of each page in the application.
Plan what you need to get Watir to do before you begin scripting. Open your web browser with the application under test in front of you, and pay close attention to the objects on that page. What text fields require entries? What buttons need to be pushed? What links need to be clicked on? It sometimes helps to write out the steps it will take to exercise a test first, and then filling in the Watir scripting code to satisfy each of those steps.
To start developing a test:
Plan what you need to get Watir to do before you begin scripting. Open your web browser with the application under test in front of you, and pay close attention to the objects on that page. What text fields require entries? What buttons need to be pushed? What links need to be clicked on? It sometimes helps to write out the steps it will take to exercise a test first, and then filling in the Watir scripting code to satisfy each of those steps.
To start developing a test:
- Open your text editor.
- Name your test file with a .rb (Ruby) extension (like test.rb).
- Provide your new test file with access to the Watir tool by entering this statement at the beginning of your test script:
require 'watir'
- Open Internet Explorer and navigate to the application you wish to test.
- Interact with it to design your test case.
- Type the corresponding Watir methods into your test script.
- Verify the results.
IE:Internet Explorer Developer Toolbar: What is IE?
Microsoft has an extension for Internet Explorer (link does not work with Firefox) that is a great addition to any tester's toolkit and is a great help when scripting web pages using Watir. This works on the DOM in the same manner that Watir does. You can explore the DOM, find elements by clicking on them and more. It's a highly recommended tool to use while writing Watir scripts.
The Internet Explorer Developer Toolbar provides several features for exploring and understanding Web pages. These features enable you to:
Navigate to Google Search, and you should see something like the following.
In this case you can see the name attribute of the field to use in your scripts. Watir can use different attributes of a tag to manipulate that object, so it is important to know what they are. In some cases the attributes are not explicit in the tag such as the text attributes.
The Internet Explorer Developer Toolbar provides several features for exploring and understanding Web pages. These features enable you to:
- Explore and modify the document object model (DOM) of a Web page.
- Locate and select specific elements on a Web page through a variety of techniques.
- View HTML object class names, ID's, and details such as link paths, tab index values, and access keys.
- Outline tables, table cells, images, or selected tags.
- Display image dimensions, file sizes, path information, and alternate (ALT) text.
- Selectively clear the browser cache and saved cookies. Choose from all objects or those associated with a given domain.
- Find the style rules used to set specific style values on an element.
- View the formatted and syntax colored source of HTML and CSS.
- Style Tracer: Right mouse click on a style value for an element and select Style Tracer to find the style rule that is effecting that value.
- View Source: View the formatted and syntax colored source of the original page, currently rendered page, element or element with the styles that are effecting it.
Navigate to Google Search, and you should see something like the following.
In this case you can see the name attribute of the field to use in your scripts. Watir can use different attributes of a tag to manipulate that object, so it is important to know what they are. In some cases the attributes are not explicit in the tag such as the text attributes.
Interacting With a Web Page
You will notice we've chosen to name the variable name ie used in Watir test scripts for the Internet Explorer browser. You could call it whatever you wish, but we use ie for ease of use. This variable tells the Watir library to exercise test scripts against an instance of the Internet Explorer web browser.
In Ruby, think of programming in terms of objects and messages. Watir was also developed with objects and messages in mind. If you think of the ie variable as an object, you can send messages to it. Think of objects as nouns. When you start up Internet Explorer, the operating system starts the program which creates an instance of the Internet Explorer web browser. You refer to this Internet Explorer browser instance as a thing. If you send a message to that object, it will respond to that message if it recognizes it.
Think of the messages as verbs. In Ruby, you send a message to an object by separating the object you are calling from the message you are sending to it with a dot. For example:
would tell the object dog that it must bark.
This isn't very specific though. What dog should bark? In the Watir world, you could identify the test area to be our yard. Like ie, treat it as an object with attributes containing other objects with attributes. For example, in our yard, there are two dogs: Heidi and Megabyte. Each of these dog objects have attributes that identify them. They have names, breeds, shapes and sizes and colors. To be more specific, and interacting with them the Watir way, you could send the message bark to the dog Heidi like this:
This says in Watir syntax: in the yard, identify the dog Heidi by her name attribute, and send her the bark message. The expected outcome would be Heidi responding to the message by barking.
When you develop test scripts with Watir, you interact with objects on a web page by sending them messages. Like the yard example, the Internet Explorer browser itself contains objects. You can access these objects within an Internet Explorer browser instance by identifying them by different attributes. Just like in the dog example, above, you must be very specific when you send messages to objects on a web page. You must also be able to identify objects on a web page by using a variety of different attributes due to the diversity in how tags are declared by different application developers. With Watir, identify objects and send them messages by using the dot notation. For example:
narrows down the type of object to send a message to.
identifies the object on the page as a button within the instance of Internet Explorer (ie) that has the value attribute (caption) Click Me. When you send the message (the verb) click, Watir interprets and tells Internet Explorer to click.
In Ruby, think of programming in terms of objects and messages. Watir was also developed with objects and messages in mind. If you think of the ie variable as an object, you can send messages to it. Think of objects as nouns. When you start up Internet Explorer, the operating system starts the program which creates an instance of the Internet Explorer web browser. You refer to this Internet Explorer browser instance as a thing. If you send a message to that object, it will respond to that message if it recognizes it.
Think of the messages as verbs. In Ruby, you send a message to an object by separating the object you are calling from the message you are sending to it with a dot. For example:
dog.bark
This isn't very specific though. What dog should bark? In the Watir world, you could identify the test area to be our yard. Like ie, treat it as an object with attributes containing other objects with attributes. For example, in our yard, there are two dogs: Heidi and Megabyte. Each of these dog objects have attributes that identify them. They have names, breeds, shapes and sizes and colors. To be more specific, and interacting with them the Watir way, you could send the message bark to the dog Heidi like this:
yard.dog(:name, "Heidi").bark
When you develop test scripts with Watir, you interact with objects on a web page by sending them messages. Like the yard example, the Internet Explorer browser itself contains objects. You can access these objects within an Internet Explorer browser instance by identifying them by different attributes. Just like in the dog example, above, you must be very specific when you send messages to objects on a web page. You must also be able to identify objects on a web page by using a variety of different attributes due to the diversity in how tags are declared by different application developers. With Watir, identify objects and send them messages by using the dot notation. For example:
ie.button
ie.button(:value, "Click Me").click
What is Watir Syntax?
The Watir syntax is shown later with three views. One is the view that we see objects on a web page while viewing them in a web browser. The next view is an example of the Watir code that would be needed to automate an action using that web page object. The third view is the object on the web page shown in its HTML form. This is the way it looks when we view the source of a web page, or open the file in a text editor.
This allows our test script to use the Watir tool.
Watir sends a message to Internet Explorer, telling to create a new instance of itself, and assigns that instance to ie.
To create an instance of Internet Explorer and navigate to the site with one statement:
Watir uses the start method to both create a browser instance and navigate to a site.
In the example above, enter in your application's URL in place of mytestsite.
Watir sends the goto message to Internet Explorer, telling it to enter the address you entered as a method argument in the Address bar, and to direct the browser to that site.
Require the Watir Tool
To use the Watir tool, first enter the following in your test script:require 'watir'
Create a Test Instance of Internet Explorer
To create a test instance of Internet Explorer, enter the following in your test script:ie = Watir::IE.new
To create an instance of Internet Explorer and navigate to the site with one statement:
ie = Watir::IE.start("http://mytestsite")
Site Navigation
To direct your test script to the web application you are testing, enter the URL in this command:ie.goto("http://mytestsite")
Watir sends the goto message to Internet Explorer, telling it to enter the address you entered as a method argument in the Address bar, and to direct the browser to that site.
How to identify Buttons in Watir
In web applications, we generally submit information we have entered or selected in the web page by clicking links, buttons and images, or by hitting Enter/Return on our keyboard.
Watir clicks buttons on a web page by looking at the attributes available in the
This is the tag in the HTML source:
This is the tag in the HTML source:
This is the Watir code you need to click a button with an image using the src attribute as a regular expression:
Watir clicks buttons on a web page by looking at the attributes available in the
HTML Buttons
What you see in the web browser:"button" id="one" name="clickme" value="Click Me">
id Attribute
This is the Watir code you need to click a button using the id attribute:ie.button(:id, "one").click
name Attribute
This is the Watir code you need to click a button using the name attribute:ie.button(:name, "clickme").click
value Attribute
This is the Watir code you need to click a button using the value attribute:ie.button(:value, "Click Me").click
Image Buttons
tag looks like an image, but acts like a button. Like HTML buttons it can be accessed by id, name and value attributes. Image buttons can also be accessed by their src attribute.src Attribute
What you see in the web browser:"image" src="images/doit.gif">
ie.button(:src, /doit/).click
How to identify Checkboxes in Watir?
Watir sets or clears checkboxes by looking at the attributes available in the HTML tag. Common attributes are id and name. For complete list see HTML Elements Supported by Watir.
What you see in the web browser:
This is the tag in the HTML source:
Watir code to clear a checkbox using the id attribute:
Watir code to clear a checkbox using the name attribute:
What you see in the web browser:
Check Me:
Check Me:"checkbox" id="one" name="checkme">
id Attribute
Watir code to set a checkbox using the id attribute:ie.checkbox(:id, "one").set
ie.checkbox(:id, "one").clear
name Attribute
Watir code to set a checkbox using the name attribute:ie.checkbox(:name, "checkme").set
ie.checkbox(:name, "checkme").clear
Watir: How to identify Links ?
You can use Watir to click links in a variety of ways. Watir can click links by looking at the link text you see in the browser or by looking at the attributes available in the HTML tag. Common attributes are id, name and href. For complete list see HTML Elements Supported by Watir.
Here is an example using a link to the Pickaxe book by the Pragmatic Programmers:
What you see in the web browser:
What you see in the HTML source:
Here is an example using a link to the Pickaxe book by the Pragmatic Programmers:
What you see in the web browser:
Pickaxe
id Attribute
Watir code to click a link using the id attribute:ie.link(:id, "one").click
name Attribute
Watir code to click a link using the name attribute:ie.link(:name, "book").click
Text
Watir code to click a link using link's text:ie.link(:text, "Pickaxe").click
href Attribute
Watir code to click a link using the href attribute:ie.link(:href, "http://pragmaticprogrammer.com/titles/ruby/").click
Watir: How to identify Radio Buttons?
Watir sets or clears radio list items by looking at the attributes available in the HTML tag. Common attributes are id and name. For complete list see HTML Elements Supported by Watir.
What you see in the web browser:
This is the tag in the HTML source:
Watir code to clear a radio list item using the id attribute:
Watir code to clear a radio list item using the name attribute:
What you see in the web browser:
Click Me:
"radio" name="clickme" id="one">
id Attribute
Watir code to set a radio list item using the and id attribute:ie.radio(:id, "one").set
ie.radio(:id, "one").clear
name Attribute
Watir code to set a radio list item using the name attribute:ie.radio(:name, "clickme").set
ie.radio(:name, "clickme").clear
Watir: How to identify Selection Boxes?
Watir sets or clears an item in a selection box (or dropdown box) by looking at the attributes available in the
Watir code to get the contents of a select list:
NOTE: contents will be an array
What you see in the web browser:
This is the tag in the HTML source:
You can set individual options using successive _set_s and you can clear everything that is selected with the clearSelection method. The following code would select every option in the select list and then clear everything.
id Attribute
Watir code to set a select box item using the id attribute:ie.select_list(:id, "one").set("is fun")
name Attribute
Watir code to set a select box item using the name attribute:ie.select_list(:name, "selectme").set("is fun")
Selection Box Methods
Watir code to clear a select box item using the id attribute:ie.select_list(:id, "one").clearSelection
contents = ie.select_list(:id, "one").getAllContents
Select Multiple
Some select lists can have multiple selections instead of just one. If multiple items can be selected in select box, Watir can set or clear an item.What you see in the web browser:
ie.select_list(:id, 'one').set('Web Testing') ie.select_list(:id, 'one').set('in Ruby') ie.select_list(:id, 'one').set('is fun') ie.select_list(:id, 'one').clearSelection
Watir:Text Fields: How to identify Text Fields in ruby scripting
Text Fields
Watir sets or clears a text field by looking at the attributes available in the HTML tag. Common attributes are id and name. For complete list see HTML Elements Supported by Watir.What you see in the web browser:
"text" id="one" name="typeinme">
There is also a file upload element that looks exactly like a text_field with a "Browse" button to the right. For directions on how to interact with this control. |
id Attribute
Watir code to set the text field with the string Watir World using the id attribute:ie.text_field(:id, "one").set("Watir World")
ie.text_field(:id, "one").clear
name Attribute
Watir code to set the text field with the string Watir World using the name attribute:ie.text_field(:name, "typeinme").set("Watir World")
ie.text_field(:name, "typeinme").clear
watir: Forms: How to identify Forms in ruby scripting?
Forms aren't visible through the browser, but are used a lot in web applications. To find them, look at the HTML source for
Watir can submit a form by looking at the attributes available in the
id Attribute
This is the Watir code you need to click a button that will submit a form using the id attribute:ie.button(:id, "one").click
Forms With No Buttons
There may be input fields on a web page, but no button to submit. Instead, they will allow you to hit Enter/Return on your keyboard. When there is no button to submit the data, we can just submit the form itself.Watir can submit a form by looking at the attributes available in the
id Attribute
Watir code to submit the form using the id attribute:ie.form(:id, "one").submit
name Attribute
Watir code to submit the form using the name attribute:ie.form(:name, "loginform").submit
action Attribute
Watir code to submit the form using the action attribute:ie.form(:action, "login").submit
method Attribute
Watir code to submit the form using the method attribute:ie.form(:method, "get").submit
watir: Frames: How to identify Frames in ruby scripting
Many web applications use frames. If you are having trouble accessing objects on a web page, be sure to check to see if the application is using frames. To find out, view the source of the page and look for or
Subscribe to:
Posts (Atom)