The Issue
At some point while testing, you will need to access a browser context menu, or other popup that is triggered by a right click, in a Ruby Watir Webdriver script. And, of course, select something from that menu.
The Solution
Watir has a right_click method built in that wraps the Selenium Webdriver (Ruby bindings) action builder context_click action.
This script (context_menu.rb) opens the context menu and selects the entry by text.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
require 'watir-webdriver' browser = Watir::Browser.new :chrome browser.goto('http://joewalnes.github.io/jquery-simple-context-menu/example.html') browser.div(:id, 'mythingy').when_present.right_click list = browser.ul(:text, /My Popup Menu/).when_present target = list.li(:text, /Cheese/).when_present target.click alert = browser.alert.when_present if alert.text =~ /clicked 5/ puts "Found the cheese." end alert.ok if list.visible? puts "Popup menu still visible." end browser.close |
If the context menu is provided by the browser, you will need to use the Selenium action builder and use send_keys to get to the option you want.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
require 'watir-webdriver' require ‘clipboard’ browser = Watir::Browser.new :firefox browser.goto('http://the-internet.herokuapp.com/context_menu') copy_link = 7 link = browser.link(:text, 'this open issue').when_present browser.driver.action.context_click(link.wd).perform (1..copy_link).each do {browser.driver.action.send_keys(:arrow_down).perform} end browser.driver.action.send_keys(:enter).perform puts Clipboard.paste browser.close |
This runs in Firefox against the link ‘this open issue’. There are a few tricks at work here.
- The Selenium action builder expects Selenium::Webdriver::Element objects wherever an element is referenced. In the .context_click call we’ve used link.wd. .wd is a Watir method that casts the Watir::[class] to a Selenium::Webdriver::Element.
- The seventh item on the Firefox context menu is ‘Copy Link Location’ so we’re using a Ruby loop to execute the arrow down 7 times.
- And we’re using Ruby gem clipboard to capture the link location and write it to the console to verify we selected the right option.
The Result
You now have some handy code in Ruby Watir Webdriver and Selenium to open and select a value from either a browser context menu, or an HTML built popup with context menu-like behavior. For other page interactions, check out our post on sending keys.