The Issue
While running through a browser test, we may need to open a link or image in a separate tab or window. If manually testing, you may choose to right click, and then select the option under the right click menu. However, a much simpler (and faster way) is to send a specific keystroke through Watir-Webdriver to directly open the browser window/tab.
The Answer
We will be utilizing a click command which will allow us to send both a ctrl-click and a shift-click to our desired element. A ctrl-click will open what we click in a new tab, and a shift-click will open the link in a new window.
1 |
b.element(:text,"XYZ").click (:shift) |
1 |
b.element(:text,"XYZ").click (:control) |
Lets utilize this command in a script.
The Code
We will navigate to the Cucumber homepage, and open a link in a new window with our shift-click command.
1 2 3 4 5 6 7 8 9 |
#ShiftClicktest.rb require 'watir-webdriver' require 'rubygems' browser = Watir::Browser.new :chrome browser.goto "https://cucumber.io/" browser.a(:text,"Training").click (:shift) browser.driver.switch_to.window(browser.driver.window_handles[1]) browser.element(:text,"Public courses").exists? puts "Text exists?: #{browser.element(:text,"Public courses").exists?} |
The Result
We can save and run our test (shiftclicktest.rb)
- Browser opens
- Browser navigates to Cucumber homepage
- Browser opens new window
- Validates text in new window
The Takeaway
Much like our send_keys command, using the control and shift click Watir-Webdriver commands will add versatility to your testing arsenal. Implement them into your automated tests and see how they can help optimize your execution.