The Issue
After doing enough basic Selenium & Watir Webdriver browser interactions, you will encounter a testing problem that will require the use of advanced user interactions, such as simulating specific inputs from a keyboard or mouse. Simulating a mouse hover is an extremely useful command. Let’s dive into how we can incorporate it into our automated tests.
The Answer
We can use the .hover command to perform a mouse hover action against an element of our choosing. It will simulate the same action as hovering your mouse over an element:
1 |
browser.link(:id,"Image1").hover |
The Code
Let’s use .hover to interact with a rollover image from a Helplogger blog page. This image will show a change when hovered over that we can visually validate:
1 2 3 4 5 6 7 |
#hoverimage.rb require 'watir-webdriver' require 'rubygems' browser = Watir::Browser.new :chrome browser.goto 'http://helplogger.blogspot.com/2012/05/create-rollover-image-effect-change.html' browser.img(:src,"http://3.bp.blogspot.com/-JhISDA9aj1Q/UTECr1GzirI/AAAAAAAAC2o/5qmvWZiCMRQ/s1600/Twitter.png").hover <br> |
Let’s try another example, this time involving rollover text validation:
1 2 3 4 5 6 7 8 |
#hovertext.rb require 'watir-webdriver' require 'rubygems' browser = Watir::Browser.new :chrome browser.goto 'http://www.scientificpsychic.com/etc/css-mouseover.html' browser.span(:class,"dropt").hover browser.span(:class,"dropt").b(:text,"Formal Description").visible? puts "Hover text visible?: #{browser.span(:class,"dropt").b(:text,"Formal Description").visible?}" |
The Result
We will save the automated test script for our first example (hoverimage.rb) and run it from the command line. Here are the resulting steps:
- Browser opens
- Browser navigates to the Helplogger blog page
- Browser hovers over image, which we can observe changing the original image
Here is the before and after for the image:
Before Hovering:
After Hovering
For the second example, we save the file (hovertext.rb)
- Browser opens
- Browser navigates to the example page with rollover text
- Browser hovers over rollover text
- Rollover text expands
- Validates that the content inside of expanded rollover text is visible
Here is the command line result for our text example:
1 2 |
C:\Users\Tester\Desktop>ruby HowToScripts.rb Hover text visible?: true |
The Takeaway
Using advance Selenium & Watir Webdriver interactions like hover will broaden the spectrum of your automated testing. Experiment within your scripts and see if you can use the hover command to solve an issue you were previously struggling with.