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.

Ruby Watir Selenium Context Menu

Context Menu, clicked by Watir

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.

Ruby Selenium Watir Context Menu

Context Menu in browser.

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.