How to Visually Verify Your Locators
This is a pseudo guest post from Brian Goad. I've adapted one of his blog posts with his permission. You can see the original blog post 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
@driver = Selenium::WebDriver.for :firefox
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
"border: 2px solid red; border-style: dashed;")
# keep element highlighted for a spell and then revert
if duration > 0
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
highlight @driver.find_element(id: 'sibling-2.3')
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.
Alternatively, you could verify your locators by using a browser plugin like FireFinder.
About The Author
You can follow Brian on Twitter at @bbbco.