Upload
himanshumanchanda2458
View
309
Download
2
Embed Size (px)
Citation preview
Ruby & WatirRuby & Watir
VariablesVariables
There are four type of variables in RubyThere are four type of variables in Ruby
- Local Variable- Local Variable
- Instance variable- Instance variable
- Class Variable- Class Variable
- Global Variable- Global Variable
Naming Convention In RubyNaming Convention In Ruby
Ruby uses a convention to help it distinguish the usage of a name: 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. the first characters of a name indicate how the name is used.
- Local variables, method parameters, and method names should all - Local variables, method parameters, and method names should all start with a lowercase letter or with an underscore. start with a lowercase letter or with an underscore.
- Global variables are prefixed with a dollar sign ($), - Global variables are prefixed with a dollar sign ($),
- instance variables begin with an ``at'' sign (@). - instance variables begin with an ``at'' sign (@).
- Class variables start with two ``at'' signs (@@). - Class variables start with two ``at'' signs (@@).
- Finally, class names, module names, and constants should start - Finally, class names, module names, and constants should start with an uppercase letterwith an uppercase letter
Methods or functions in RubyMethods or functions in Ruby
Methods are defined with the keyword def, Methods are defined with the keyword def, followed by the method name and the method's followed by the method name and the method's parameters between parentheses.parameters between parentheses.
you simply finish the body with the keyword end. you simply finish the body with the keyword end.
Example – Example –
def generateDynamicUsernameAndPassworddef generateDynamicUsernameAndPassword ---code in this section---code in this section
endend
def test_checkUserLoginStatusdef test_checkUserLoginStatus ---code in this section---code in this section
endend
Control StructuresControl Structures
Ruby has all the usual control structures, such as if Ruby has all the usual control structures, such as if
statements and while loopsstatements and while loops or For ... Inor For ... In
Example- Example- if (statement) thenif (statement) then
-- code-- codeendend
for i in 1..3 for i in 1..3 print i, " " print i, " "
endend
Exception handling in RubyException handling in Ruby
We enclose the code that could raise an We enclose the code that could raise an exception in a begin/end block and use rescue exception in a begin/end block and use rescue clauses to tell Ruby the types of exceptions we clauses to tell Ruby the types of exceptions we want to handle. want to handle.
beginbegin
assert($ie.div(:id,divId ).exists?)assert($ie.div(:id,divId ).exists?)
logPasslogPass
rescue => erescue => e
handleFail ehandleFail e
endend
Output Page Output Page
InheritanceInheritance
Inheritance allows you to create a class that is a refinement Inheritance allows you to create a class that is a refinement or specialization of another class.or specialization of another class.
Example- Example- class AbstractPage < TestBaseclass AbstractPage < TestBase
def test_checkRightsLinkFromAbstractPagedef test_checkRightsLinkFromAbstractPage
----code----code
endend
endend
The “< TestBase” on the class definition line tells Ruby that an The “< TestBase” on the class definition line tells Ruby that an AbstractPage is a subclass of TestBase. Class AbstractPage AbstractPage is a subclass of TestBase. Class AbstractPage inherits the methods of class TestBase.inherits the methods of class TestBase.
Regular ExpressionRegular Expression
A regular expression is simply a way of specifying a pattern of characters to be matched in a 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 string. In Ruby, you typically create a regular expression by writing a pattern between slash characters (/pattern/)characters (/pattern/)
If the string has some special character, use backslash(\) before it to escape it.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 OMIM logo image", "OMIM logo image", /omim.gif/)els_check_image_elements("Validating Jump To Abstract image", "Jump To Abstract image", /btn\els_check_image_elements("Validating Jump To Abstract image", "Jump To Abstract image", /btn\_jumpAbstract\.gif/)_jumpAbstract\.gif/)
els_click_link_text("click Link 'view OMIM term' ", "view OMIM term")els_click_link_text("click Link 'view OMIM term' ", "view OMIM term")II els_attach_url(/ncbi\.nlm\.nih\.gov/) thenels_attach_url(/ncbi\.nlm\.nih\.gov/) then
els_check_text("Validate OMIM term in the pop-up window", "AMELOGENIN; AMELX")els_check_text("Validate OMIM term in the pop-up window", "AMELOGENIN; AMELX")close_ie_forAutoLoginclose_ie_forAutoLoginrestore_old_ierestore_old_ie
endend
els_click_link_text("click OMIM term from the article", "Amelogenin")els_click_link_text("click OMIM term from the article", "Amelogenin")if els_attach_url(/ncbi\.nlm\.nih\.gov/) thenif els_attach_url(/ncbi\.nlm\.nih\.gov/) then
els_check_text("Validate OMIM term in the pop-up window", "AMELOGENIN; AMELX")els_check_text("Validate OMIM term in the pop-up window", "AMELOGENIN; AMELX")close_ie_forAutoLoginclose_ie_forAutoLoginrestore_old_ierestore_old_ie
endend
Installation directoryInstallation directory
Watir unit test example directoryWatir unit test example directory
How do I…How do I…
Navigate the browser?Navigate the browser?Find elements on the page?Find elements on the page?Interact with elements on the page?Interact with elements on the page?Check output on the page?Check output on the page?Create and use Methods?Create and use Methods?Create formal test cases?Create formal test cases?
Navigating the BrowserNavigating the Browser
# Always Load the Watir library at the top of your script# Always Load the Watir library at the top of your scriptrequire 'watir'require 'watir'
#Start IE and navigate to a given URL#Start IE and navigate to a given URL ie = Watir::IE.start()ie = Watir::IE.start()
#or..Attach to an existing IE window by title or url#or..Attach to an existing IE window by title or urlie = Watir::IE.attach(ie = Watir::IE.attach(:title:title,'title'),'title')ie = Watir::IE.attach(ie = Watir::IE.attach(:url:url,/regex matching url/),/regex matching url/)
#Navigate to a different URL#Navigate to a different URLie.goto("http://journals.elsevierhealth.com/")ie.goto("http://journals.elsevierhealth.com/")
#Close IE.#Close IE.ie.closeie.close
Finding <HTML> ElementsFinding <HTML> Elements
Common Functions of the IE object:Common Functions of the IE object:
TextBoxTextBox IE.text_field(IE.text_field(how, whathow, what))
ButtonButton IE.button(IE.button(how, whathow, what))
DropDownListDropDownList IE.select_list(IE.select_list(how, whathow, what))
CheckBoxCheckBox IE.checkbox(IE.checkbox(how, whathow, what))
RadioButtonRadioButton IE.radio(IE.radio(how, whathow, what))
HyperLinkHyperLink IE.link(IE.link(how, whathow, what))
FormForm IE.form(IE.form(how, whathow, what))
FrameFrame IE.frame(IE.frame(how, whathow, what))
And many, many more (div, label, image, etc…)…And many, many more (div, label, image, etc…)…
How’s and What’sHow’s and What’s
How’s:How’s:
:name:name
:id:id
:index:index
:value:value
:text:text
:title:title
What’s:What’s:
String value of String value of “how” “how”
/Regular /Regular expression/expression/
How’s tell your method how to find the element How’s tell your method how to find the element you’re looking for. What’s tell your method the you’re looking for. What’s tell your method the value for “how”.value for “how”.
Interacting with ElementsInteracting with Elements
#Set the text field (or text area) specified name specified value.#Set the text field (or text area) specified name specified value. ie.text_field(ie.text_field(:name:name,'name').set('value') ,'name').set('value')
#Sets the select with to the specified value#Sets the select with to the specified valueie.select_list(ie.select_list(:name:name,'name').select('value') ,'name').select('value')
#Click the button with the specified value (label)#Click the button with the specified value (label)ie.button(ie.button(:value:value,'value').click,'value').click
#Clicks the link matching 'text'#Clicks the link matching 'text' ie.link(ie.link(:text:text,'text').click,'text').click
#Accessing elements in a "frame" or "iframe"#Accessing elements in a "frame" or "iframe"ie.frame(ie.frame(:name:name,"someFrame").text_field(,"someFrame").text_field(:name:name,'name').set('value'),'name').set('value')
Checking OutputChecking Output
#Get the title of the page#Get the title of the pageie.titleie.title
#Get all the text displayed on the page#Get all the text displayed on the pageie.textie.text
#Get all the HTML in the body of the page#Get all the HTML in the body of the pageie.htmlie.html
#Return true if ‘text’ is displayed on the page#Return true if ‘text’ is displayed on the pageie.contains_text('text')ie.contains_text('text')
Creating simple TestCreating simple Test
require 'watir'require 'watir'
ie= Watir::IE.newie= Watir::IE.new
ie.goto("academicradiology.org")ie.goto("academicradiology.org")
puts "navigate to Academic Radiology url"puts "navigate to Academic Radiology url"
ie.text_field(:name, "username").set("userlive")ie.text_field(:name, "username").set("userlive")
puts "enter username"puts "enter username"
ie.text_field(:name, "password").set("password")ie.text_field(:name, "password").set("password")
puts "enter password"puts "enter password"
ie.button(:value, "SIGN IN").clickie.button(:value, "SIGN IN").click
puts "click Submit button"puts "click Submit button"
ie.contains_text("Welcome")ie.contains_text("Welcome")
puts "Validate user logged in"puts "Validate user logged in"
ie.closeie.close
Result outputResult output
Creating Formal Test CasesCreating Formal Test Casesrequire 'watir'require 'watir'
require 'test/unit'require 'test/unit'
require 'test/unit/ui/console/testrunner'require 'test/unit/ui/console/testrunner'
class SimpleTestSuiteclass SimpleTestSuite < Test::Unit::TestCase < Test::Unit::TestCase
def test_checkUserLoginStatusdef test_checkUserLoginStatus
ie= Watir::IE.newie= Watir::IE.new
ie.goto("academicradiology.org")ie.goto("academicradiology.org")
puts "navigate to Academic Radiology url"puts "navigate to Academic Radiology url"
ie.text_field(:name, "username").set("userlive")ie.text_field(:name, "username").set("userlive")
puts "enter username"puts "enter username"
ie.text_field(:name, "password").set("password")ie.text_field(:name, "password").set("password")
puts "enter password"puts "enter password"
ie.button(:value, "SIGN IN").clickie.button(:value, "SIGN IN").click
puts "click Submit button"puts "click Submit button"
ie.contains_text("Welcome")ie.contains_text("Welcome")
puts "Validate user logged in"puts "Validate user logged in"
ie.closeie.close
endend
def test_validateMessageForUnsuccessfulLogindef test_validateMessageForUnsuccessfulLogin
ie= Watir::IE.newie= Watir::IE.new
ie.goto("academicradiology.org")ie.goto("academicradiology.org")
puts "navigate to Academic Radiology url"puts "navigate to Academic Radiology url"
beginbegin
assert(ie.link(:text,"Logout").exists?)assert(ie.link(:text,"Logout").exists?)
ie.link(:text,"Logout").clickie.link(:text,"Logout").click
puts "logging out the user as it is already logged in"puts "logging out the user as it is already logged in"
rescue => erescue => e
# do nothing# do nothing
endend
ie.text_field(:name, "username").set("wrongUser")ie.text_field(:name, "username").set("wrongUser")
puts "enter username"puts "enter username"
ie.text_field(:name, "password").set("wrongpassword")ie.text_field(:name, "password").set("wrongpassword")
puts "enter password"puts "enter password"
ie.button(:value, "SIGN IN").clickie.button(:value, "SIGN IN").click
puts "click Submit button"puts "click Submit button"
strResult = ie.contains_text("Welcome")strResult = ie.contains_text("Welcome")
if(strResult) then if(strResult) then
puts "Validate user logged in" puts "Validate user logged in"
elseelse
puts "user not logged in"puts "user not logged in"
endend
ie.closeie.close
endend
endend
Result OutputResult Output
Creating and using MethodsCreating and using Methodsdef startTest(testName)def startTest(testName)
@ie = Watir::IE.new@ie = Watir::IE.new
endend
def endTestdef endTest
endend
def navigate_to_url(url)def navigate_to_url(url)
@ie.goto(url)@ie.goto(url)
endend
def enter_test_into_text_field(textFieldName, value)def enter_test_into_text_field(textFieldName, value)
@ie.text_field(:name, textFieldName).set(value)@ie.text_field(:name, textFieldName).set(value)
endend
def click_button(btnName)def click_button(btnName)
@ie.button(:value, btnName)[email protected](:value, btnName).click
endend
def validate_text(expected)def validate_text(expected)
@ie.contains_text(expected)@ie.contains_text(expected)
endend
def log_user_out_if_user_is_loggedIndef log_user_out_if_user_is_loggedIn
beginbegin
assert(@ie.link(:text,"Logout").exists?)assert(@ie.link(:text,"Logout").exists?)
@ie.link(:text,"Logout")[email protected](:text,"Logout").click
puts "logging out the user as it is already logged in"puts "logging out the user as it is already logged in"
rescue => erescue => e
# do nothing# do nothing
endend
endend
def test_checkUserLoginStatusdef test_checkUserLoginStatus
startTest("checkUserLoginStatus")startTest("checkUserLoginStatus")
navigate_to_url("http://www.academicradiology.org")navigate_to_url("http://www.academicradiology.org")
enter_test_into_text_field("username", "userlive")enter_test_into_text_field("username", "userlive")
enter_test_into_text_field("password", "password")enter_test_into_text_field("password", "password")
click_button("SIGN IN")click_button("SIGN IN")
validate_text("Welcome")validate_text("Welcome")
endTestendTest
endend
def test_validateMessageForUnsuccessfulLogindef test_validateMessageForUnsuccessfulLogin
startTest("checkUserLoginStatus")startTest("checkUserLoginStatus")
navigate_to_url("http://www.academicradiology.org")navigate_to_url("http://www.academicradiology.org")
log_user_out_if_user_is_loggedInlog_user_out_if_user_is_loggedIn
enter_test_into_text_field("username", "wrongUser")enter_test_into_text_field("username", "wrongUser")
enter_test_into_text_field("password", "wrongPassword")enter_test_into_text_field("password", "wrongPassword")
click_button("SIGN IN")click_button("SIGN IN")
validate_text("Welcome")validate_text("Welcome")
endTestendTest
endend
def test_checkUserLoginStatusdef test_checkUserLoginStatusie= Watir::IE.newie= Watir::IE.newie.goto("academicradiology.org")ie.goto("academicradiology.org")puts "navigate to Academic Radiology url"puts "navigate to Academic Radiology url"ie.text_field(:name, "username").set("userlive")ie.text_field(:name, "username").set("userlive")puts "enter username"puts "enter username"ie.text_field(:name, "password").set("password")ie.text_field(:name, "password").set("password")puts "enter password"puts "enter password"ie.button(:value, "SIGN IN").clickie.button(:value, "SIGN IN").clickputs "click Submit button"puts "click Submit button"ie.contains_text("Welcome")ie.contains_text("Welcome")puts "Validate user logged in"puts "Validate user logged in"ie.closeie.close
endend
File handling and Result generationFile handling and Result generationdef startTest(testName)def startTest(testName)
@ie = Watir::IE.new@ie = Watir::IE.new@reportFile = File.new("C:/apps/sampleTest/Result/" +testName + ".html", "w")@reportFile = File.new("C:/apps/sampleTest/Result/" +testName + ".html", "w")@reportFile.write("<HTML><TITLE></TITLE><table border = '1' bgcolor = 'Aquamarine' >")@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>")@reportFile.write("<tr><td colspan = '3' align = 'center' bgcolor = 'Yellow'><font size ='5'>"+ testName + "</font></td></tr>")
endenddef endTestdef endTest
@[email protected]@[email protected]
endenddef navigate_to_url(step,url)def navigate_to_url(step,url)
@ie.goto(url)@ie.goto(url)@reportFile.write("<tr><td>"+step+ "</td><td> navigating to: " +url +"</td><td bgcolor='Aquamarine'>pass</td></tr>")@reportFile.write("<tr><td>"+step+ "</td><td> navigating to: " +url +"</td><td bgcolor='Aquamarine'>pass</td></tr>")
endenddef enter_test_into_text_field(step,textFieldName, value)def enter_test_into_text_field(step,textFieldName, value)
@ie.text_field(:name, textFieldName).set(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>")@reportFile.write("<tr><td>"+step+ "</td><td> entering text to : " +textFieldName +"</td><td bgcolor='Aquamarine'>pass</td></tr>")
endenddef click_button(step,btnName)def click_button(step,btnName)
@ie.button(:value, btnName)[email protected](:value, btnName)[email protected]("<tr><td>"+step+ "</td><td> click button: " +btnName +"</td><td bgcolor='Aquamarine'>pass</td></tr>")@reportFile.write("<tr><td>"+step+ "</td><td> click button: " +btnName +"</td><td bgcolor='Aquamarine'>pass</td></tr>")
endenddef validate_text(step,expected)def validate_text(step,expected)
txt= @ie.contains_text(expected)txt= @ie.contains_text(expected)if(txt) thenif(txt) then
@reportFile.write("<tr><td>"+step+ "</td><td> Expected : " +expected +"</td><td bgcolor='Aquamarine'>pass</td></tr>")@reportFile.write("<tr><td>"+step+ "</td><td> Expected : " +expected +"</td><td bgcolor='Aquamarine'>pass</td></tr>")elseelse
@reportFile.write("<tr><td>"+step+ "</td><td> Expected text: " +expected+" not found</td><td bgcolor='red'>fail</td></tr>")@reportFile.write("<tr><td>"+step+ "</td><td> Expected text: " +expected+" not found</td><td bgcolor='red'>fail</td></tr>")endend
endenddef log_user_out_if_user_is_loggedIndef log_user_out_if_user_is_loggedIn
beginbeginassert(@ie.link(:text,"Logout").exists?)assert(@ie.link(:text,"Logout").exists?)@ie.link(:text,"Logout")[email protected](:text,"Logout").clickputs "logging out the user as it is already logged in"puts "logging out the user as it is already logged in"
rescue => erescue => e# do nothing# do nothing
endendendenddef test_checkUserLoginStatusdef test_checkUserLoginStatus
startTest("checkUserLoginStatus")startTest("checkUserLoginStatus")navigate_to_url("Navigate to Academicradiology home page","http://www.academicradiology.org")navigate_to_url("Navigate to Academicradiology home page","http://www.academicradiology.org")log_user_out_if_user_is_loggedInlog_user_out_if_user_is_loggedInenter_test_into_text_field("Enter Username","username", "userlive")enter_test_into_text_field("Enter Username","username", "userlive")enter_test_into_text_field("Enter Password","password", "password")enter_test_into_text_field("Enter Password","password", "password")click_button("Click SIGN IN button","SIGN IN")click_button("Click SIGN IN button","SIGN IN")validate_text("Validate Welcome text after login", "xxxWelcome")validate_text("Validate Welcome text after login", "xxxWelcome")endTestendTest
endend
Directory where results are savedDirectory where results are saved
Result with Pass statusResult with Pass status
Result with FailureResult with Failure
Running multiple test suiteRunning multiple test suite
To run multiple test suite, two file are required –To run multiple test suite, two file are required –
1)1) all_tests.rb – which calls all the test suiteall_tests.rb – which calls all the test suite
2)2) Set-up.rb file - where global variables are defined and test suite Set-up.rb file - where global variables are defined and test suite from the particular directory are selected.from the particular directory are selected.
all_test.rball_test.rb
$LOAD_PATH.unshift File.dirname( ".")$LOAD_PATH.unshift File.dirname( ".")
$LOAD_PATH.unshift File.dirname("primaryTestcases/.")$LOAD_PATH.unshift File.dirname("primaryTestcases/.")
require 'primary_setup'require 'primary_setup'
$all_tests.each {|testName| require testName}$all_tests.each {|testName| require testName}
$LOAD_PATH all refer to the array of load paths. Within Ruby code $LOAD_PATH all refer to the array of load paths. Within Ruby code you can access and modify the load path that determines where you can access and modify the load path that determines where “require” and “load” look for files“require” and “load” look for files
set_up.rbset_up.rbBEGIN {BEGIN {$logDirectory="C:/apps/sampleTest/Result/"$logDirectory="C:/apps/sampleTest/Result/"$failBgColor="HotPink"$failBgColor="HotPink"$headBgColor="Yellow"$headBgColor="Yellow"$main_result_file_content = "<HTML><BODY><TABLE align='center' border='1' bgcolor='" + $passBgColor +"'>"$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'> $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>"Watir Test Results </font></TD></TR>"}}
END {END {summary_report_file = File.new($logDirectory + "/TestResults.html", "w")summary_report_file = File.new($logDirectory + "/TestResults.html", "w")$main_result_file_content = $main_result_file_content + "</BODY></TABLE></HTML>"$main_result_file_content = $main_result_file_content + "</BODY></TABLE></HTML>"summary_report_file.write $main_result_file_contentsummary_report_file.write $main_result_file_contentsummary_report_file.closesummary_report_file.close
exit!(1)exit!(1) endend $ie.close$ie.close}}
require 'watir'require 'watir'require 'test/unit'require 'test/unit'require 'test/unit/ui/console/testrunner'require 'test/unit/ui/console/testrunner'include Watirinclude Watir
testsdir = File.join(File.dirname(__FILE__), 'primaryTestcases')testsdir = File.join(File.dirname(__FILE__), 'primaryTestcases')
Dir.chdir testsdir doDir.chdir testsdir do$all_tests = Dir["watir_*.rb"]$all_tests = Dir["watir_*.rb"]$testsFailed="false"$testsFailed="false"endend
$ie = Watir::IE.new$ie = Watir::IE.new$ie.set_fast_speed$ie.set_fast_speed
Results for multiple TestSuiteResults for multiple TestSuite