_ruby
TL;DR - Show Me The Code
require 'selenium-webdriver'
require 'rspec/expectations'
include RSpec::Matchers
def setup
@driver = Selenium::WebDriver.for(:firefox)
end
def teardown
@driver.quit
end
def run
setup
yield
teardown
end
run do
@driver.get 'https://the-internet.herokuapp.com/windows'
@driver.switch_to.new_window(:window)
@driver.get('https://the-internet.herokuapp.com/typos')
expect(@driver.window_handles.size).to eql 2
end
run do
@driver.get 'https://the-internet.herokuapp.com/windows'
@driver.switch_to.new_window(:tab)
@driver.get('https://the-internet.herokuapp.com/typos')
expect(@driver.window_handles.size).to eql 2
end
Code Walkthrough
Importing Libraries
First, we are pulling in our requisite classes (e.g., selenium-webdriver
to drive the browser,
and rspec/expectations
& RSpec::Matchers
for our assertion).
Setup and Teardown
Next, we are setting up and tearing down the browser instance. We're using the setup
method to launch a new
instance of Firefox with Selenium and storing it in a class variable that we'll use throughout all tests. After our
test executes the teardown
method will execute. This calls driver.quit()
which ends the session by closing the
browser instance.
The run
method is a custom method that we've defined to execute our test. It's a simple wrapper around the setup
and teardown
methods. We're using it to keep our test code clean and easy to read.
Open New Window
The first test shows how to open a new window, switch to it, and assert the number of window handles open. They key
to this is the @driver.switch_to.new_window(:window)
line. Which opens a new window and switches to it.
Open New Tab
The second test shows how to open a new tab, switch to it, and assert the number of window handles open. They key to
this is the @driver.switch_to.new_window(:tab)
line. Which opens a new tab and switches to it.
Executing the Test
Before executing the test, we need to make sure the required dependencies are declared on the Gemfile
file.
Toggle to see the Gemfile
file.
source 'https://rubygems.org'
gem 'rspec', '~> 3.10'
gem 'selenium-webdriver', '~> 4.26.0'
Finally, we can run the test by executing ruby new_window_and_tab.rb
from the command-line.