Vous êtes sur la page 1sur 30

Ruby & Watir

Variables

There are four type of variables in Ruby

- Local Variable

- Instance variable

- Class Variable

- Global Variable
Naming Convention In Ruby

Ruby uses a convention to help it distinguish the usage of a name: the first characters
of a name indicate how the name is used.

- Local variables, method parameters, and method names should all start with a
lowercase letter or with an underscore.

- Global variables are prefixed with a dollar sign ($),

- instance variables begin with an ``at'' sign (@).

- Class variables start with two ``at'' signs (@@).

- Finally, class names, module names, and constants should start with an uppercase
letter
Methods or functions in Ruby

Methods are defined with the keyword def, followed by the


method name and the method's parameters between
parentheses.
you simply finish the body with the keyword end.

Example –

def generateDynamicUsernameAndPassword
---code in this section
end

def test_checkUserLoginStatus
---code in this section
end
Control Structures

Ruby has all the usual control structures, such as if statements and while loops
or For ... In

Example-
if (statement) then
-- code
end

for i in 1..3   
print i, " "
end
Exception handling in Ruby

We enclose the code that could raise an exception in a


begin/end block and use rescue clauses to tell Ruby the types
of exceptions we want to handle.

begin
assert($ie.div(:id,divId ).exists?)
logPass
rescue => e
handleFail e
end
Output Page
Inheritance

Inheritance allows you to create a class that is a refinement or specialization of


another class.
Example-
class AbstractPage < TestBase
def test_checkRightsLinkFromAbstractPage
----code
end
end

The “< TestBase” on the class definition line tells Ruby that an AbstractPage is a
subclass of TestBase. Class AbstractPage inherits the methods of class TestBase.
Regular Expression
A regular expression is simply a way of specifying a pattern of characters to be matched in a
string. In Ruby, you typically create a regular expression by writing a pattern between slash
characters (/pattern/)
If the string has some special character, use backslash(\) before it to escape it.

els_check_image_elements("Validating OMIM logo image", "OMIM logo image", /omim.gif/)


els_check_image_elements("Validating Jump To Abstract image", "Jump To Abstract image",
/btn\_jumpAbstract\.gif/)

els_click_link_text("click Link 'view OMIM term' ", "view OMIM term")


I els_attach_url(/ncbi\.nlm\.nih\.gov/) then
els_check_text("Validate OMIM term in the pop-up window", "AMELOGENIN; AMELX")
close_ie_forAutoLogin
restore_old_ie
end

els_click_link_text("click OMIM term from the article", "Amelogenin")


if els_attach_url(/ncbi\.nlm\.nih\.gov/) then
els_check_text("Validate OMIM term in the pop-up window", "AMELOGENIN; AMELX")
close_ie_forAutoLogin
restore_old_ie
end
Installation directory
Watir unit test example directory
How do I…

Navigate the browser?


Find elements on the page?
Interact with elements on the page?
Check output on the page?
Create and use Methods?
Create formal test cases?
Navigating the Browser

# Always Load the Watir library at the top of your script


require 'watir'

#Start IE and navigate to a given URL


ie = Watir::IE.start()

#or..Attach to an existing IE window by title or url


ie = Watir::IE.attach(:title,'title')
ie = Watir::IE.attach(:url,/regex matching url/)

#Navigate to a different URL


ie.goto("http://journals.elsevierhealth.com/")

#Close IE.
ie.close
Finding <HTML> Elements

Common Functions of the IE object:

TextBox IE.text_field(how, what)


Button IE.button(how, what)
DropDownList IE.select_list(how, what)
CheckBox IE.checkbox(how, what)
RadioButton IE.radio(how, what)
HyperLink IE.link(how, what)
Form IE.form(how, what)
Frame IE.frame(how, what)

And many, many more (div, label, image, etc…)…


How’s and What’s
How’s tell your method how to find the element you’re looking
for. What’s tell your method the value for “how”.

How’s:
What’s:
:name
String value of
:id
“how”
:index /Regular expression/
:value
:text
:title
Interacting with Elements

#Set the text field (or text area) specified name specified value.
ie.text_field(:name,'name').set('value')

#Sets the select with to the specified value


ie.select_list(:name,'name').select('value')

#Click the button with the specified value (label)


ie.button(:value,'value').click

#Clicks the link matching 'text'


ie.link(:text,'text').click

#Accessing elements in a "frame" or "iframe"


ie.frame(:name,"someFrame").text_field(:name,'name').set('value')
Checking Output

#Get the title of the page


ie.title

#Get all the text displayed on the page


ie.text

#Get all the HTML in the body of the page


ie.html

#Return true if ‘text’ is displayed on the page


ie.contains_text('text')
Creating simple Test

require 'watir'

ie= Watir::IE.new

ie.goto("academicradiology.org")
puts "navigate to Academic Radiology url"

ie.text_field(:name, "username").set("userlive")
puts "enter username"

ie.text_field(:name, "password").set("password")
puts "enter password"

ie.button(:value, "SIGN IN").click


puts "click Submit button"

ie.contains_text("Welcome")
puts "Validate user logged in"

ie.close
Result output
require 'watir'
require 'test/unit'
require 'test/unit/ui/console/testrunner'
Creating Formal Test Cases
class SimpleTestSuite < Test::Unit::TestCase
def test_checkUserLoginStatus
ie= Watir::IE.new
ie.goto("academicradiology.org")
puts "navigate to Academic Radiology url"
ie.text_field(:name, "username").set("userlive")
puts "enter username"
ie.text_field(:name, "password").set("password")
puts "enter password"
ie.button(:value, "SIGN IN").click
puts "click Submit button"
ie.contains_text("Welcome")
puts "Validate user logged in"
ie.close
end
def test_validateMessageForUnsuccessfulLogin
ie= Watir::IE.new
ie.goto("academicradiology.org")
puts "navigate to Academic Radiology url"
begin
assert(ie.link(:text,"Logout").exists?)
ie.link(:text,"Logout").click
puts "logging out the user as it is already logged in"
rescue => e
# do nothing
end
ie.text_field(:name, "username").set("wrongUser")
puts "enter username"
ie.text_field(:name, "password").set("wrongpassword")
puts "enter password"
ie.button(:value, "SIGN IN").click
puts "click Submit button"
strResult = ie.contains_text("Welcome")
if(strResult) then
puts "Validate user logged in"
else
puts "user not logged in"
end
ie.close
end
end
Result Output
Creating and using Methods
def startTest(testName)
@ie = Watir::IE.new
end
def endTest
@ie.close
end
def navigate_to_url(url)
@ie.goto(url)
end
def enter_test_into_text_field(textFieldName, value) def test_checkUserLoginStatus
@ie.text_field(:name, textFieldName).set(value)
end
ie= Watir::IE.new
def click_button(btnName) ie.goto("academicradiology.org")
@ie.button(:value, btnName).click puts "navigate to Academic Radiology url"
end
def validate_text(expected)
ie.text_field(:name, "username").set("userlive")
@ie.contains_text(expected) puts "enter username"
end ie.text_field(:name, "password").set("password")
def log_user_out_if_user_is_loggedIn
puts "enter password"
begin
assert(@ie.link(:text,"Logout").exists?) ie.button(:value, "SIGN IN").click
@ie.link(:text,"Logout").click puts "click Submit button"
puts "logging out the user as it is already logged in"
ie.contains_text("Welcome")
rescue => e
# do nothing puts "Validate user logged in"
end ie.close
end end
def test_checkUserLoginStatus
startTest("checkUserLoginStatus")
navigate_to_url("http://www.academicradiology.org")
enter_test_into_text_field("username", "userlive")
enter_test_into_text_field("password", "password")
click_button("SIGN IN")
validate_text("Welcome")
endTest
end
def test_validateMessageForUnsuccessfulLogin

startTest("checkUserLoginStatus")
navigate_to_url("http://www.academicradiology.org")
log_user_out_if_user_is_loggedIn
enter_test_into_text_field("username", "wrongUser")
enter_test_into_text_field("password", "wrongPassword")
click_button("SIGN IN")
validate_text("Welcome")
endTest
end
File handling and Result generation
def startTest(testName)
@ie = Watir::IE.new
@reportFile = File.new("C:/apps/sampleTest/Result/" +testName + ".html", "w")
@reportFile.write("<HTML><TITLE></TITLE><table border = '1' bgcolor = 'Aquamarine' >")
@reportFile.write("<tr><td colspan = '3' align = 'center' bgcolor = 'Yellow'><font size ='5'>"+ testName + "</font></td></tr>")
end
def endTest
@ie.close
@reportFile.close
end
def navigate_to_url(step,url)
@ie.goto(url)
@reportFile.write("<tr><td>"+step+ "</td><td> navigating to: " +url +"</td><td bgcolor='Aquamarine'>pass</td></tr>")
end
def enter_test_into_text_field(step,textFieldName, value)
@ie.text_field(:name, textFieldName).set(value)
@reportFile.write("<tr><td>"+step+ "</td><td> entering text to : " +textFieldName +"</td><td bgcolor='Aquamarine'>pass</td></tr>")
end
def click_button(step,btnName)
@ie.button(:value, btnName).click
@reportFile.write("<tr><td>"+step+ "</td><td> click button: " +btnName +"</td><td bgcolor='Aquamarine'>pass</td></tr>")
end
def validate_text(step,expected)
txt= @ie.contains_text(expected)
if(txt) then
@reportFile.write("<tr><td>"+step+ "</td><td> Expected : " +expected +"</td><td bgcolor='Aquamarine'>pass</td></tr>")
else
@reportFile.write("<tr><td>"+step+ "</td><td> Expected text: " +expected+" not found</td><td bgcolor='red'>fail</td></tr>")
end
end
def log_user_out_if_user_is_loggedIn
begin
assert(@ie.link(:text,"Logout").exists?)
@ie.link(:text,"Logout").click
puts "logging out the user as it is already logged in"
rescue => e
# do nothing
end
end
def test_checkUserLoginStatus
startTest("checkUserLoginStatus")
navigate_to_url("Navigate to Academicradiology home page","http://www.academicradiology.org")
log_user_out_if_user_is_loggedIn
enter_test_into_text_field("Enter Username","username", "userlive")
enter_test_into_text_field("Enter Password","password", "password")
click_button("Click SIGN IN button","SIGN IN")
validate_text("Validate Welcome text after login", "xxxWelcome")
endTest
end
Directory where results are saved
Result with Pass status
Result with Failure
Running multiple test suite

To run multiple test suite, two file are required –

1) all_tests.rb – which calls all the test suite


2) Set-up.rb file - where global variables are defined and test suite
from the particular directory are selected.
all_test.rb

$LOAD_PATH.unshift File.dirname( ".")


$LOAD_PATH.unshift File.dirname("primaryTestcases/.")
require 'primary_setup'
$all_tests.each {|testName| require testName}

$LOAD_PATH all refer to the array of load paths. Within Ruby code you can access
and modify the load path that determines where “require” and “load” look for files
set_up.rb
BEGIN {
$logDirectory="C:/apps/sampleTest/Result/"
$failBgColor="HotPink"
$headBgColor="Yellow"
$main_result_file_content = "<HTML><BODY><TABLE align='center' border='1' bgcolor='" + $passBgColor +"'>"
$main_result_file_content = $main_result_file_content + "<TR><TD colspan='2' align ='center' bgcolor='" + $headBgColor +"'><font size='6'> Watir Test Results </font></TD></TR>"
}

END {
summary_report_file = File.new($logDirectory + "/TestResults.html", "w")
$main_result_file_content = $main_result_file_content + "</BODY></TABLE></HTML>"
summary_report_file.write $main_result_file_content
summary_report_file.close

exit!(1)
end

$ie.close
}

require 'watir'
require 'test/unit'
require 'test/unit/ui/console/testrunner'
include Watir

testsdir = File.join(File.dirname(__FILE__), 'primaryTestcases')

Dir.chdir testsdir do
$all_tests = Dir["watir_*.rb"]
$testsFailed="false"
end

$ie = Watir::IE.new
$ie.set_fast_speed
Results for multiple TestSuite

Vous aimerez peut-être aussi