This is a pseudo guest post from Brian Goad. I've adapted a blog post of his with permission. You can see the original here. Brian is a Test Engineer at Digitalsmiths. You can follow him on Twitter at @bbbco and check out his testing blog here.
It's likely that you'll run into odd test behavior that makes you question the locators you're using in a test. But how do you interrogate your locators to make sure they are doing what you expect?
Let's take a look at an example.
For our initial setup let's pull in the
selenium-webdriver gem and wire up some simple
# filename: highlight.rb require 'selenium-webdriver' def setup @driver = Selenium::WebDriver.for :firefox end def teardown @driver.quit end def run setup yield teardown end
Now let's create a
highlight helper method that will accept a Selenium WebDriver
element and a time to wait (e.g.,
duration) as arguments.
By setting a duration, we can control how long to highlight an element on the page before reverting the styling back. And we can make this an optional argument by setting a default (e.g., 3 seconds).
def highlight(element, duration = 3) # store original style so it can be reset later original_style = element.attribute("style") # style element with yellow border @driver.execute_script( "arguments.setAttribute(arguments, arguments)", element, "style", "border: 2px solid red; border-style: dashed;") # keep element highlighted for a spell and then revert if duration > 0 sleep duration @driver.execute_script( "arguments.setAttribute(arguments, arguments)", element, "style", original_style) end end
There are three things going on here.
- We store the style of the element so we can revert it back when we're done
- We change the style of the element so it visually stands out (e.g., a red dashed border)
- We revert the style of the element back after 3 seconds
setAttribute function. And we're executing it with Selenium's
Now to use this in our test is simple, we just prepend a
find_element action with the
run do @driver.get 'http://the-internet.herokuapp.com/large' highlight @driver.find_element(id: 'sibling-2.3') end
If you were to save this file and run it (e.g.,
ruby highlight.rb from the command-line), here is what you would see.
- Load the page
- Find the element
- Change the styling of the element so it has a red dashed-line border
- Wait 3 seconds
- Revert the styling to remove the border
If you wanted to take this a step further, you could leverage this approach along with an interactive debugger. You can read more about how to do that here in Brian's other guest post.
Alternatively, you could verify your locators by using a browser plugin like FireFinder. You can read more about how to do that here in this previous tip.