Tutorials

Convert Drop-Down to Array

Written by Aidy.

It's possible to convert a drop-down to an array using just one line of code like so.

optionsArray = b.select_list(:id, 'options1').options.map(&:value)

As you can see we've created a variable called optionsArray and then assigned all the values from the specified dropdown to that variable as an array.

Now let's have a look at a couple of examples where this could be used.

Select Last Value From Drop-Down
Suppose you had a test that didn't care what the values were in a drop-down and you just wanted to make sure you always selected the last option from the list. This could be used to test something like the most expensive postage option for an online store or the largest t-shirt size. This is an example of how you can do that. This piece of code will open the test site and select the last option from the drop-down.

require "watir-webdriver"
b = Watir::Browser.new :chrome
b.goto 'http://www.lazyautomation.co.uk/lazy1.html'

optionsArray = b.select_list(:id, 'options1').options.map(&:value)
b.select_list(:id, 'options1').select_value(optionsArray[-1])

As you can we've navigated to the test site and then assigned all the values from the drop-down to an array.

The values in the array are indexed starting from 0. We can select any of those values by referencing the index in squared brackets. E.g. optionsArray[0] would be the first value from the dropdown. [-1] which is what we've used in this instance goes back one and selects the last value.

Select Random Value From Drop-Down
It may 
occasionally be useful to add randomness to some tests, the code below will open up the test page and select a random option from the drop-down. Try running this multiple times to see different values get selected.

require "watir-webdriver"
b = Watir::Browser.new :chrome
b.goto 'http://www.lazyautomation.co.uk/lazy1.html'

randomNumber = rand(0..2) 
optionsArray = b.select_list(:id, 'options1').options.map(&:value)
b.select_list(:id, 'options1').select_value(optionsArray[randomNumber])

Instead of using an actual number for the index of optionsArray, this time around we've put a variable in there called randomNumber. Line 5 assigns a random number between 0 and 2 to randomNumber. There are three options in the drop down on the test page if there were 4 then obviously you'd need to increase the range to between 0 and 3 e.g. rand(0..3).