The Issue

You need to separate data from code to keep things DRY (Don’t Repeat Yourself). You have a lot of browser elements to locate that will be used in a lot of scripts and you don’t have, or have time to set up, a DBMS (database management system) and the glue code to access it. The solution? An object repository in Excel/CSV for Selenium Webdriver, Ruby.

The Solution

You can readily put the volatile stuff (anything that could change almost certainly will) in a two dimensional table structure in a spreadsheet worksheet or in a CSV file. It looks like this:

data_driven_objects

All values in the first column must be unique and all values in the first (header) row must be unique.

‘Name’ is the name we will use in the code to look up the other three values.
‘Type’ is the tag name (or synonym used by Watir Webdriver) of the HTML Element (object) we are looking for.
‘Identifier’ is the element attribute by which we will identify it, and
‘Value’ is the string we’ll use to know we’ve got the right instance.

Loading the Data

For spreadsheets we’ll use the Ruby Gem Roo, a quick and reliable utility for reading spreadsheets including Excel .xlsx, Open Office .ods, and other fairly common formats.

This method will read all worksheets in the spreadsheet. It assumes all are two dimensional tables like the ‘objects’ sheet above. It will put the data in an instance variable named with the sheet name, e.g., ‘objects’ is loaded to @objects, etc.

Loading from CSV uses the Ruby standard module CSV and is straightforward.  The only thing to remember is that each look up has to be loaded with a separate call to the method.

Look Up the Data

Now we need to extract the locator information (type, identifier, value) from the hash.

With Roo, the @objects instance variable is a regular Ruby hash of hashes. For element location we want an array containing type, identifier, and value, in that order. CSV is initially in a bit different internal format so this method converts to the Ruby hash before looking up the stuff we want.

Invoke and use it like this:

The Result

With relatively few lines of code, and three methods, we have a robust and flexible way of keeping the code DRY and the data separate in our Ruby Selenium Webdriver scripts. Please take a look at our How To section for more Webdriver info, including How to use Xpath to find browser elements.