The Issue
Regular expression in Ruby allows us to interact with an element that contains the value we are looking for in a string, instead of the exact value. In Ruby, a string is a group of letters/characters that constitute readable text, text that we wish to display to someone. A regular expression is a pattern that is matched with the given string, and tells if there is a match or not. The pattern can be as simple as a single string, or extremely complex. We’ll limit ourselves to a few simple variations that can help a lot in making Watir Webdriver/Selenium Scripts more friendly and flexible.
The Code
The regular expression (a.k.a. regexp) is bounded between forward slashes (/…./). and is matched against a string object with the ‘=~’ operator. Take a look at the below example:
1 2 3 4 5 6 7 8 9 10 |
puts puts('Rescue: fail unless story list contains "Trump"') stream = @browser.ul(:id, 'Stream') if <em>stream.text =~ /Trump/</em> puts('Found Trump') else puts('No Trump at the moment') end |
Here we combine our if/else/then statements and create a script that will fail unless the script finds a story containing /Trump/. We can also insert a local variable into the regexp, using ‘#{variable}’, as seen below:
1 2 3 4 5 6 7 8 9 |
target = 'Trump' puts puts("Regular Expression: Does the story list contain \"#{target}\"") stream = @browser.ul(:id, 'Stream') if stream.text =~ <em>/#{target}/</em> puts("Found #{target}") else puts("No #{target} at the moment") end |
The Takeaway
Working in Ruby, we can incorporate regular expression into our Watir Webdriver/Selenium automation to add another tool to our validation arsenal. Regular expression provides utility in Cucumber feature files as well, allowing us to add the same logic to a step definition.