Ruby · selenium · Selenium-webdriver · watir · yaml

Configuration Management using YAML file for Watir/Selenium web-driver related frameworks

Requirement:

In watir/selenium webdriver related automation framework, how can we run the same script in multiple environments.

Code:

config.yml:

Beta:
url: "beta.google.com"

Gamma:
url: "gamma.google.com"

Prod:
url: "google.com"

Code.rb

require 'rubygems'
require 'yaml'
require 'watir-webdriver'
$env= ARGV[0]
config = YAML.load_file("config.yml")
$browser=Watir::Browser.new :ie
puts "Navigating to #{config[$env]["url"]}"
$browser.goto("#{config[$env]["url"]}")

Output:

in CMD PROMPT>ruby code.rb Beta

Navigating to beta.google.com

in CMD PROMPT>ruby code.rb Prod

Navigating to google.com

cheat sheet · QA · Ruby · Ruby 1.9 · ruby excercise · selenium · selenium-webdriver · Selenium-webdriver · watir · watir-webdriver

Custom HTML report for Ruby(Watir/Selenium) Base Automation framework

Requirement:

Sample HTML report for any ruby based Automation Testing Framework

Installation/Changes :

1. Create code.rb file and paste the below code.

2. Create folder named as Results in the same location.

Code:

def get_time_name
$time=Time.now
$time_name="#{$time.hour.to_s}-#{$time.min.to_s}-#{$time.sec.to_s}-#{$time.day.to_s}-#{$time.mon.to_s}-#{$time.year.to_s}"
$result_date = "#{$time.day.to_s}-#{$time.month.to_s}-#{$time.year.to_s}"
end
def create_report
get_time_name
@result_file_name="Report"+"-"+$time_name
@full_file_name="Results/#{@result_file_name}.html"
$report=File.open(@full_file_name,'w')
end
def insert_head_title(title)
$report.puts "<html><head>
<title> #{title} </title>
</head>"
end
def start_table
$report=File.open(@full_file_name,'a')
$report.puts "<table border=1>
<tr>
<th>Test Case Name</th>
<th>Test Case Description</th>
<th>Browser Name</th>
<th>Result</th>
<th>Remarks</th>
</tr>"
$report.close
end
def insert_reportname_date(name,date)
$report.puts "<body bgcolor='#5CB3FF'>
<p align='left' size=2>
<b><img src='https://encrypted-tbn1.google.com/images?q=tbn:ANd9GcQB0l0xnGOHuRPFMMMi-OVg39nfAU1Ogvxr7Okk7DD8ZpqlMF9r'></img> </b>
</p>
<p size=12>
<center> <b><u>#{name} </u></b></center>
</p>
<p align='right' size=12>
<b>Date: #{date} </b>
</p>"
$report.close
end
def report_row(*details)
$report=File.open(@full_file_name,'a')
name=details[0]
desc=details[1]
browser=details[2]
result=details[3]
reason=details[4]
if result.downcase == "pass"
$report.puts "<tr>
<td>#{name}</td>
<td> #{desc}</td>
<td> #{browser} </td>
<td bgcolor='green'>#{result}</td>
<td>#{reason}</td>
</tr>"
else
$report.puts "<tr>
<td>#{name}</td>
<td> #{desc}</td>
<td> #{browser} </td>
<td bgcolor='red'>#{result}</td>
<td>#{reason}</td>
</tr>"
end
$report.close
end
def close_table
$report=File.open(@full_file_name,'a')
$report.puts "</table></br>"
$report.close
end
def summary_report(overall,passed,failed)
$report_overall=overall
$report_pass=passed
$report_fail=failed
$report=File.open(@full_file_name,'a')
$report.puts "<p> <b>Total Test cases : #{$report_overall} </b></p>
<p> <b>Passed : #{$report_pass} </b></p>
<p> <b>Failed : #{$report_fail} </b></p>
</body>
</html>"
$report.close
end

create_report
insert_head_title("Raveendran -- Sample HTML Report")
insert_reportname_date("My Test Report",$result_date )
start_table
report_row("Check Google Home Page","Check The Title in Google Home Page","IE","PASS","Title Present")
report_row("Check Google Home Page","Check The Title in Google Home Page","FF","FAIL","Title Not Present")
close_table
summary_report(2,1,1)

 

Output HTML File:

Ruby · selenium · Selenium-webdriver · watir

Get the Version detail of opened Selenium/Watir Webdriver Browser

Code for Selenium WebDriver IE Browser :

require 'rubygems'

require 'selenium-webdriver'

br=Selenium::WebDriver.for :ie

ie=br.execute_script("return navigator.userAgent;")

# Ex. "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET4.0C)"

puts ie.split("MSIE ")[1].split(";")[0]

OUTPUT  –> 9.0

——————————————————————————————————————————————-

Code for Selenium WebDriver Firefox Browser :

require 'selenium-webdriver'

br=Selenium::WebDriver.for :ff

ff=br.execute_script("return navigator.userAgent;")

# Ex. "Mozilla/5.0 (Windows NT 6.1; rv:12.0) Gecko/20100101 Firefox/12.0"

puts ff.split("/")[-1]

OUTPUT  –> 12.0

——————————————————————————————————————————————-

Code for Watir WebDriver IE Browser :

require 'rubygems'

require 'watir-webdriver'

br=Watir::Browser.new :ie

ie=br.execute_script("return navigator.userAgent;")

puts ie.split("MSIE ")[1].split(";")[0]

OUTPUT  –> 9.0

——————————————————————————————————————————————-

Code for Watir WebDriver Firefox Browser :

require 'rubygems'

require 'watir-webdriver'

br=Watir::Browser.new :ff

ff=br.execute_script("return navigator.userAgent;")

puts  ff.split("/")[-1]

OUTPUT  –> 12.0

——————————————————————————————————————————————-

Ruby · watir

What’s new on Watir 3

Change log is quite long, but reading it makes your life easier:
* Browser #status returns an empty string if status bar is disabled in IE9
* Browser #style fixed for IE9
* #execute_script evaluates JavaScript code inside of an anonymous function
– use “return” statement if value is needed by Ruby
* #execute_script returns nil instead of ‘undefined’
* drag and drop fixed for IE9
* Window#current? and Window#== are more robust
* all html elements are now supported (even html5 ones)
* CookieManager removed
* cookies API support added (

https://github.com/watir/watirspec/blob/master/cookies_spec.rb)

* drag and drop API support added (

https://github.com/watir/watirspec/blob/master/drag_and_drop_spec.rb)

* Element#(before|after)? removed
* Element#(before|after)_text removed
* Browser#cell(s) and Browser#row(s) removed
* Browser#Element camelCase methods removed, use under_score methods instead
* Browser#element(s) supports only general attributes like :id, :title,
:class_name, :text, :html and such
* Browser#modal_dialog improved
* Browser#send_keys and Element#send_keys have now same syntax as specified
in WatirSpec
* Element#style returns internal styles only for IE9, inline style will be
returned for IE8
* Table#each removed – use Table#(trs|rows).each instead
* Table#row(s) and Table#cell(s) added which ignore inner tables – use
#td/#tr for all.
* raise an Exception if more locators are specified with :xpath/:css
* searching by :xpath and :css code rewritten
* Browser#textarea(s) method for searching elements
* Element#focus works with IE9
* Element#focused? returns the state of focus on that element
* Element#to_subtype returns Element if non-supported tag found instead of
crashing
* searching by :class will match now partially like other tools behave
(e.g. jQuery)
* Button#text returns value if exists instead of text
* Browser#goto prepends url automatically with http:// if scheme is missing
* Browser#element(s)_by_(xpath/css) are now private methods – use
#element(:css => …) and #element(:xpath => …) instead
* Browser#label supports searching by :for attribute
* Browser#options method for searching elements
* Browser#body, #thead, #tfoot, #tbody, #frameset and #fieldset added
* Browser#window and Browser#windows added implementing window switching
API (https://github.com/jarib/watirspec/blob/master/window_switching_spec.rb)
* Element#present? returns false if exception is thrown by #exists? or #visible?
* Element#style returns CSS text instead of OLE object
* Element#text returns an empty string for non-visible elements
* Element#parent returns correct instance of Element class (e.g. Div
instead of Element)
* Element#focus focuses document before focusing on the element
* Element#right_click and Element#double_click added
* Element#to_subtype added which returns specific instance of
Watir::Element subclass
* Element#send_keys added
* Element#eql? as an alias for Element#== added
* Element#tag_name added
* ElementCollection#[] method supports negative indexes like regular Arrays
* ElementCollection#[] returns always an object, even if the index is out of bounds
* FileField#set and Image#save uses correct Windows file path (e.g. convert “\”-es into “/”-es)
* FileField#set raises Errno::ENOENT instead of WatirException if file
doesn’t exist
* FileField#value= as an alias for FileField#set added
* Font#color, #face and #size added
* Form#submit triggers onSubmit event and doesn’t submit the form if
event’s callback returns false
* Frame#execute_script added
* Image#file_size, #height and #width return integer instead of a string
* Image#save blocking fixed
* Meta#content and #http_equiv added
* Option code rewritten, causing changes in its API
* SelectList code rewritten, causing changes in its API
* SelectList#(selected_)options returns now Options collection instead ofan array of strings
* Table and its subelements code rewritten, causing changes in its API
* Table#strings and #hashes added
* TextField#label added
* searching elements will find only correct types – e.g. using Browser#div
returns only DIV element even if all other provided selectors match
* all selectors and tag of the element needs to match even if searching by:id
* supporting html5 data-* attributes by using :data_* for locating and
#data_* for retrieving attribute values
* many other internal changes

Please try it out by executing:
gem install watir

Auto Complete · Slider · Testing · watir · watir-webdriver

Automate JQuery Slider using Watir-WebDriver

Automate JQuery Slider using Watir-WebDriver:

Example Code:

require ‘rubygems’
require ‘watir-webdriver’

ie=Watir::Browser.new :ie
ie.goto(“http://jqueryui.com/demos/slider/&#8221;)
ie.link(:class,’ui-slider-handle ui-state-default ui-corner-all’).focus
ie.send_keys(:arrow_down)
ie.send_keys(:page_down)
ie.send_keys(:arrow_up)
ie.send_keys(:page_up)

 

Demo Output Video  —  http://bit.ly/j_slider

cucumber · QA · rspec · Testing · watir

RSpec + Watir WebDriver

Installation:

1. Install Ruby

2. CMD>gem install watir-webdriver

3. CMD>gem install rspec

Code:

google_search.rb

require 'rubygems'
require 'watir-webdriver'

class Google
def search(browser,term,result)

if browser.downcase=="ie"
br= :ie
elsif browser.downcase=="ff"
br= :ff
elsif browser.downcase=="chrome"
br= :chrome
else
br= :ie
end

$ie=Watir::Browser.new br
$ie.goto("http://google.com")
$ie.text_field(:name,'q').set(term)
sleep 3
$ie.button(:name,'btnG').click
sleep 3
$result=$ie.text.downcase.include?(result)

$ie.close
end

end

googleSearch_spec.rb

require 'rubygems'
require 'rspec'
require 'google_search'

describe Google, "#Searchresult" do
it "returns the expected result in search result page" do
bowling = Google.new
bowling.search("chrome","Raveendran","ruby")
$result.should eq(true)
end
end

describe Google, "#Searchresult" do
it "returns the expected result in search result page" do
bowling = Google.new
bowling.search("chrome","Raveendran","wordpress")
$result.should eq(true)
end
end

describe Google, "#Searchresult" do
it "returns the expected result in search result page" do
bowling = Google.new
bowling.search("chrome","Watir, Selenium,Cucumber highline","raveendran")
$result.should eq(true)
end
end

describe Google, "#Searchresult" do
it "returns the expected result in search result page" do
bowling = Google.new
bowling.search("chrome","Ruby highline","raveendran")
$result.should eq(true)
end
end

RUN THE RSPEC code:

1. Navigate to the folder where files available

>rspec googleSearch_spec.rb

 

OUTPUT:

It will launch Chrome browser and will execute the test cases. Finally You will get the output like,

Started ChromeDriver
port=4113
version=14.0.836.0
.Started ChromeDriver
port=4164
version=14.0.836.0
.Started ChromeDriver
port=4218
version=14.0.836.0
.Started ChromeDriver
port=4260
version=14.0.836.0
.

Finished in 77.28 seconds
4 examples, 0 failures

 

Jazzez · pdf-reader · Prawn · Ruby · Ruby 1.9 · ruby excercise · watir

Convert Webpage into PDF files using Ruby gems — Watir-Webdriver + Prawn

Installation : 

1. Install Ruby 1.8.7 or 1.9.2

2. Install WatirWebdriver — Refer  http://rubygems.org/gems/watir-webdriver

a. CMD>gem install watir-webdriver

3. Install Prawn Library

a. CMD>gem install prawn

Sample Code:

require 'rubygems'
require 'watir-webdriver'
require 'prawn'

ff=Watir::Browser.new :ff

ff.goto("https://raveendran.wordpress.com")

Prawn::Document.generate('c:\\test123\\hello.pdf') do |pdf|
pdf.text(ff.text)
end

ff.close

Output:

hello PDF  file contains all the TEXT from Webpage

 

Open Issues:

Alignment issue occurs depends upon web page Design. But You wont miss to collect all the Text from Webpage.

Blogroll · Google Charts · Ruby · Ruby 1.9 · watir · watir-webdriver

Chart Creation using Ruby Gems — Google Charts + Watir WebDriver

Installation : 

1. Install Ruby 1.8.7 or 1.9.2

2. Install WatirWebdriver — Refer  http://rubygems.org/gems/watir-webdriver

a. CMD>gem install watir-webdriver

3. Install Google Charts Library — Refer http://googlecharts.rubyforge.org/

Sample Code:

require 'rubygems'
require 'watir-webdriver'
require 'gchart'

ff=Watir::Browser.new :ff

first=Gchart.bar(:data => [300, 100, 30, 200])
ff.goto(first)
ff.driver.save_screenshot 'c:\\test123\\first.jpg'

second=Gchart.pie_3d(:title => 'Open Source Tools', :size =>
'400x200',:data => [45, 35, 20], :labels => ["Watir", "Selenium", "Others"] )
ff.goto(second)
ff.driver.save_screenshot 'c:\\test123\\second.jpg'
three=Gchart.line(:data => [300, 100, 30, 200, 100, 200, 300, 10],
:axis_with_labels => 'x,r',:axis_labels => [['Jan','July','Jan','July','Jan'], ['2005','2006','2007']])
ff.goto(three)
ff.driver.save_screenshot 'c:\\test123\\three.jpg'

ff.close

Output:

1. Usually Google Charts gives  http urls as a output. Using Watir WebDriver we can open the URL and navigate to the mentioned page and we can save that web page as a Image.

2.  Run the code –> The out folder contains the images

Ruby · watir · watir-webdriver

Watir WebDriver — Handling New Window

Situation:

1. You are in Parent Page.
2. Clicking link “Open” in Parent page.
3. It opens new window
4. You need to do actions  there and come back to your parent window

Solution:

To Click the Link

require 'rubygems'
require 'watir-webdriver'
ff=Watir::Browser.new :ff
ff.goto("website.com")
ff.link(:text,'open').click

To handle the New window and performing some actions within that window,

ff.window(:title,/TITLE of the new window/i).use do
ff.send_keys('SampleText')
ff.button(:id,'insert').click
puts ff.title #returns the new window title
end

within a loop The button belongs to Newly opened window.

puts ff.title #returns the parent window title

cheat · cheat sheet · QA · Ruby 1.9 · ruby excercise · watir · watir-webdriver

Watir-webdriver cheatsheet

Getting Started

Load the Watir Webdriver library

require 'watir-webdriver'

Open a browser (Ex: Internet Explorer)

driver = Watir::Browser.new :ie

Go to a specified URL

driver.goto 'http://www.orbitz.com/'

Close the browser

driver.close

Access an Element

Type something in the Text box or text area

driver.text_field(:id,'airOrigin').set("MAA")

To Clear the text from text field 

driver.text_field(:id,'airOrigin').clear

Button

To click the button
driver.button(:id,'BUTTON_ID'').click

Drop down list

To select the value from list
driver.select_list(:id,'airStartTime').select("1 am")

To get the selected value from select field
 driver.select_list(:id,'airStartTime').value

Check box

To clik the check box

driver.checkbox(:id,'airNonStopsPreferred').click
OR
driver.checkbox(:id,'airNonStopsPreferred').set
To know the clicked? or not ?
driver.checkbox(:id,'airNonStopsPreferred').set?

Radio button driver.radio(:id,'htlChoice').click

To verify Flights radio button selected or not

driver.radio(:id,'htlChoice').set?

#if it returns TRUE then radio button already selected.

To get the title of the webpage puts driver.title

Return true if the specified text appears on the TAG

 puts driver.li(:class,'welcomeText').text.include("Welcome to Orbitz")

To Click SPAN Elements driver.span(:text,'Find Flights').click