Ruby & Selenium-WebDriver Tutorial – Part 1: Writing our first test

September 25, 2013  |  Automation, QA, Ruby, Selenium

In our last post, Advanced Seleneium IDE Tutotrial, we created an automated test case to search Google for SeleniumHQ. Now, we’re going to look at that test in Ruby utilizing Selenium-WebDriver (and search for Selenium Tutorials instead!).

You might ask ‘Why Ruby?’ or say ‘I don’t know any Ruby!’. Ruby is an excellent choice for writing Selenium tests because how easy it is to learn as well as how easy it is to read. In this short segment, we aren’t even going to teach any Ruby yet, we’re going to show how simple Ruby is to read that you don’t even need to know any beforehand to follow along!

Let’s first take a look at the complete example first.

require ‘selenium-webdriver’

driver = Selenium::WebDriver.for :firefox
driver.navigate.to "http://google.com"

element = driver.find_element(:name, 'q')
element.send_keys "Selenium Tutorials"
element.submit

driver.quit

These couple of lines are all we need to remake our Selenium IDE test into a Ruby & Selenium-WebDriver test! Let’s examine the code line by line.

The first one require 'selenium-webdriver' just brings the selenium-webdriver library into our code so that we can use it. With that done, we can now control the browser with Ruby.

The next two lines driver = Selenium::WebDriver.for :firefox and driver.navigate.to "http://google.com" basically create an object from where we can control the browser. We can do all sorts of things with the driver object such as navigating to pages, finding elements, and closing itself. The next three lines find an element, the search input, using the driver object, types in Selenium Tutorials, and then submits the form. One of the great benefits of Ruby is how obvious looking the code is, you can tell without knowing any Ruby what the code is doing. Finally, we close the driver (browser).

As we can see, Ruby is pretty easy to read. Coupled with Selenium-WebDriver, we can write powerful tests that go beyond what we can do with the IDE.