Thursday, October 28, 2010

Finding HTML Elements in Watir

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…)…

Test Unit

Test::Unit is a library of Ruby (just like Watir)

It is not technically part of Watir…however it is used regularly to structure tests.

To use Test::Unit in your scripts you ‘require’ it just as you do watir

require ‘test/unit’
require ‘watir’

Test::Unit is a way to organize your code into “tests”

Test::Unit has built in methods called “assertions” that help your tests with validation.

assert(browser.link(:text, “Click Here”).exists?)

The above statement will return a TRUE or FALSE indicating a pass or fail in your test.

Below is the basic code structure of a class in Test unit

require 'test/unit’

    class TC_MyTest < Test::Unit::TestCase
    include Watir

    def setup        #optional
    end            #optional
    def teardown      #optional
    end             #optional

        def test_pass
            assert(something.exists?)
        end
    end 


Watir Recorders

Watir is not a record/playback tool. However, there are several recorders “out there”

WatirMaker:

 It is a utility for Watir test developers which will record actions in a browser. It comes in two flavors: the C# version, and the Ruby version

Watir WebRecorder:

WebRecorder is an action recorder for web applications. A version that creates Watir scripts was released in February 2006. A handy tool to help learn Watir.Free, but not open source

Webmetrics RIA Script Recorder:

The script recorder is a tool to help generate a working watir script that can be used with the Webmetrics Rich Internet Application Monitoring. Webmetrics RIA Monitoring utilizes the open source technology Watir to do performance monitoring.

Tuesday, September 21, 2010

Exception handling in Ruby

The Ruby Exception Handling mechanism includes:

1. rescue and final clauses - for handling unwanted errors and
exit gracefully.

2. raise - for deliberately creating and raising exceptions in
code.

3. catch and throw clause - for continuing execution at some
point up the function call stack


I have been mainly using rescue in my code and have managed to handle most of the exceptions.

Example

i=0
while i<=10
  begin
    if i ==0
      1/0
    end
    raise "random exception"
   rescue ZeroDivisionError
    i+=1
  end
end

Rescuing Exceptions Inside Methods

def  foo_method
  puts "Hi"  raise
  puts "Bye"
rescue
  puts "Rescuing exceptions"

Adding support for html elements in WATIR

Any HTML element or tag can be to WATIR framework by updating non_control_elements.rb in watir framework.

1. Go to C:\ruby\lib\ruby\gems\1.8\gems\watir-1.6.5\lib\watir
2. Open non_control_elements.rb and add tags which are not there in the list and you wish to validate

class Ul < NonControlElement
    TAG = 'UL'
  end
  class H1 < NonControlElement
    TAG = 'H1'
  end
  class H2 < NonControlElement
    TAG = 'H2'
  end
class LEGEND < NonControlElement
    TAG = 'LEGEND'
  end
  class TH < NonControlElement
    TAG = 'TH'
  end

This can be then used to validate any text/links/listboxes etc on the html page.

Monday, August 23, 2010

Keyboard simulation in WATIR

Example:
 
ie.send_keys("{APPSKEY}")---Command for Right click
ie.send_keys("{ENTER}")---Command for Enter key
ie.send_keys("{LCTRL}")---Command for Left Control

Below are some common key codes:

Browser commands:

{BROWSER_BACK}---2000/XP Only: Command for browser "back" button
{BROWSER_FORWARD}---2000/XP Only: Command for browser "forward" button
{BROWSER_REFRESH}---2000/XP Only: Command for browser "refresh" button

Functional keys:

{PRINTSCREEN}---Command for Print Screen  button 
{CTRLDOWN}---Holds the CTRL key down until {CTRLUP} is sent
{SHIFTDOWN}---Holds the SHIFT key down until {SHIFTUP} is sent
{SHIFTDOWN}---Holds the SHIFT key down until {SHIFTUP} is sent 
 

Tuesday, July 27, 2010

Handling popups in Watir

Sometimes when a user is using a web page a pop-up window appears. These requires special attention in watir.

Pop-Up examples:   
Security Alerts
Choose File pop-ups
Save As
Login (username/password) panels
Alert boxes
Script prompt/textbox
Confirmation Boxes (ok/cancel)


Code to Handle pop ups
 
require 'watir'
require 'watir/dialog'

link = 'http://anylink'

ie = Watir::IE.start(link)
# Use click_no_wait
ie.button(:value, 'Display alert box').click_no_wait  
dialog = Watir::Dialog.new
# Use the sleep method with any value you need
sleep 0.4
 # Click on Popup window button
dialog.button('OK').click 
 ie.waitForIE

I came across situation where I needed to handle popups on click of radio button as well. Above can also be extended to radiobuttons, checkboxes and other objects as well.

ie.radio(:id,"xyz").click_no_wait
sleep 0.4
dialog = Watir::Dialog.new
dialog.button('OK').click 
 ie.waitForIE

Tuesday, July 20, 2010

Drag and Drop using Watir:

I had hard time doing this since none of the posts on the net worked. There are couple of posts which talks about it and has methods as well but there is no complete step by step information or guide. So i thought i would add one here and this is how I did it for IE.
Go to element.rb file of WATIR library and this is where all IE actions reside. This should be at C:\ruby\lib\ruby\gems\1.8\gems\watir-1.6.5\lib\watir if u have installed ruby on c:\
Add below code for supporting drag and drop functionality
def top_edge
assert_exists
assert_enabled
ole_object.getBoundingClientRect.top.to_i
end
def top_edge_absolute
top_edge + page_container.document.parentWindow.screenTop.to_i
end
def left_edge
assert_exists
assert_enabled
ole_object.getBoundingClientRect.left.to_i
end
def left_edge_absolute
left_edge + page_container.document.parentWindow.screenLeft.to_i
end
def right_click
x = left_edge_absolute
y = top_edge_absolute
#puts "x: #{x}, y: #{y}"
WindowsInput.move_mouse(x, y)
WindowsInput.right_click
end
def left_click
x = left_edge_absolute
y = top_edge_absolute
#puts "x: #{x}, y: #{y}"
# need some extra push to get the cursor in the right area
WindowsInput.move_mouse(x + 2, y + 2)
WindowsInput.left_click
end
def drag_drop(target, src_offset=1, dst_offset=1)
drag_x = left_edge_absolute + src_offset
drag_y = top_edge_absolute + src_offset
drop_x = target.left_edge_absolute + dst_offset
drop_y = target.top_edge_absolute + dst_offset
WindowsInput.move_mouse(drag_x, drag_y)
WindowsInput.left_down
WindowsInput.move_mouse(drop_x, drop_y)
WindowsInput.left_up
end
Many sites will give you this code but below methods are critical here and none talks about it
def left_down
leftdown = create_mouse_input(MOUSEEVENTF_LEFTDOWN)
send_input( [leftdown] )
end
def left_up
leftup = create_mouse_input(MOUSEEVENTF_LEFTUP)
send_input( [leftup] )
end
Now you are all set for it to work. Use it like
$ie.link(:href,"any url1").drag_drop($ie.link(:href,"any url2"),1,100)
any url1 is object to be dragged and any url 2 is where it needs to be dropped. Drag and Drop objects can be same or different. It will be same if you want to move only one object. 1 is source offset i.e. starting position and 100 is destination offset i.e. ending position. Both offsets are not mandatory.
ie.div(:id, 'src').drag_drop(ie.div(:id, 'dst'))