_ruby
A Solution
WebDriver works with each of the major browsers through a browser driver which is (ideally) maintained by the browser manufacturer. It is an executable file (consider it a thin layer or a shim) that acts as a bridge between Selenium and the browser.
ChromeDriver is Google Chrome's browser driver. In this specific use case is of using WebDriver with Chrome in testing locally.
Let's step through an example using ChromeDriver (download here).
Example
Before starting, we'll need to download the latest ChromeDriver binary executable from here. Once we have it we'll need to tell Selenium where it is. Two ways we can do this are to:
- Add it to the System PATH
- Specify it in the Selenium setup
We'll start by pulling in our requisite libraries (e.g., selenium-webdriver
to driver the browser and rspec/expectations
& RSpec::Matchers
to perform an assertion) and wiring up some simple setup
, teardown
, and run
methods.
# filename: chrome.rb
require 'selenium-webdriver'
require 'rspec/expectations'
include RSpec::Matchers
def setup
Selenium::WebDriver::Chrome::Service.driver_path = "C:\\tmp\\chromedriver.exe"
@driver = Selenium::WebDriver.for :chrome
end
def teardown
@driver.quit
end
def run
setup
yield
teardown
end
Notice that in setup
we are telling Selenium where the ChromeDriver exectuable is with driver_path
before creating an instance of the browser.
Now we're ready to add a simple test.
# filename: chrome.rb
# ...
run do
@driver.get 'http://the-internet.herokuapp.com/'
expect(@driver.title).to eql 'The Internet'
end
If we save this file and run it (e.g., ruby chrome.rb
) it will launch an instance of Chrome, visit the homepage of the-internet, and assert that the page title loaded.
Expected Behavior
When we save this file and run it (e.g., ruby chrome.rb
from the command-line) here is what will happen.
- ChromeDriver starts
- Chrome opens
- Test runs
- Chrome closes
- ChromeDriver stops
Summary
Hopefully this tip has helped you get a better handle on how WebDriver works with various browsers and saved you some time in your configuration setup. But keep in mind that no two browser drivers are alike, so be sure to check out the documentation for the browser you care about to find out it's specific requirements. For more about specific driver requirements, visit the official Selenium Quick Reference page for Installing Browser Drivers.
Happy Testing!