In this article, I will show you how to get started with writing a basic Selenium WebDriver test with the Ruby programming language using a Mac.

Prerequisites

Selenium WebDriver

Open the command prompt on your operating system and execute the command below.

gem install selenium-webdriver

(If you already have the gem installed make sure you have version 3.4.1 or higher.)

ChromeDriver

Download and install the latest version of ChromeDriver

Unzip Chromedriver and add the executable to /usr/local/bin

Or if using Homebrew.

brew install chromedriver

I will be writing the code in a text editor. My preferred text editor is Sublime. But you can use any such as Atom, TextWrangler, Xcode

Writing your first test - Opening a browser

To be able to perform some basic tests. First, we need to open a web browser. This very basic test below will launch an instance of chrome browser and navigate to Google.co.uk

#WebDriver gem loaded in to interact with Selenium.

require 'selenium-webdriver'

# create a webdriver object to interact with.

driver = Selenium::WebDriver.for :chrome

# enter the url you wish to navigate to.

driver.navigate.to "https://www.google.co.uk/"

# maximize the browser window.

driver.manage,window.maximize

Clicking an element on the web page

That is great we have run our first test and opened an instance of Chrome web browser and navigated to Google.co.uk

But what can we do now we have got here? Let’s navigate to Gmail.

#WebDriver gem loaded in to interact with Selenium.

require 'selenium-webdriver'

# create a webdriver object to interact with.

driver = Selenium::WebDriver.for :chrome

# enter the url you wish to navigate to.

driver.navigate.to "https://www.google.co.uk/"

# maximize the browser window.

driver.manage,window.maximize

# create a wait with a timeout of 15 seconds.

wait = Selenium::WebDriver::wait.new(timeout: 15)

# use an implicit wait click the Gmail link from google.co.uk web page

link = wait.until 
element = driver.find_element(:link_text, "Gmail")
element if element.displayed?
}
link.click()

#quitting the browser.

driver.quit

Our basic test is now completed. The test will open up google.co.uk in Chrome, click the “Gmail” link from the homepage and then close the Chrome web browser.

Running the Test

To execute the test file. Navigate to the location of the saved file in terminal/cmd and execute the following cmd. Remember to enter the name of your saved file and remove the brackets.

ruby <nameofyourfile>.rb

Russell Morley

Software Developer In Test | Automation Enthusiast