The Issue
In Ruby, an array is a list of objects. A common use of an array in Watir Webdriver/Selenium automation is to step through each item (object) and do something to it. Usually the same thing is done with each object in the array. It can be defined in a couple ways. The simplest is enclosing a comma-delimited list of items in square brackets.
The Code
We define our array here as “targets”. Within, we have placed our text and divided each item by commas. After, we have created a function that will use the each. do command to perform actions for each item (each returns all the elements of an array/hash). The script will check if there is any text containing the items we have defined (using regular expression). It will then output text indicating we have found the object if we have, and text indicating there is no object if we have not.
1 2 3 4 5 6 7 8 9 10 11 12 |
targets = ['Trump', 'Arrest', 'Tweet', 'reveal'] puts puts("Array: Does the story list contain one or more of #{targets}?") stream = @browser.ul(:id, 'Stream') targets.each do |target| if stream.text =~ /#{target}/i puts("Found '#{target}'") else puts("No '#{target}' at the moment") end |
The output will display as follows:
1 2 3 4 5 |
Array: Does the story list contain one or more of '["Trump", "Arrest", "Tweet", "reveal"]'? Found 'Trump' No 'Arrest' at the moment No 'Tweet' at the moment No 'reveal' at the moment |
The Takeaway
Arrays are a cornerstone of Ruby; in an automation context, they expand our options and allow us to affect commands on multiple variables at once. Much like other Ruby concepts, the application of arrays can be quite vast, so experiment and see how you can implement them within your Watir Webdriver/Selenium test scripts.