Why you should use CSS selectors for your WebDriver tests

I didn’t used to be a fan of CSS selectors for automated web tests, but I changed my mind.

The reason I didn’t use to be a fan of CSS selectors is that historically they weren’t really encouraged by Watir, since the Watir API was designed to find elements by type and attribute, so the Watir API would look something like:

browser.div(:class => 'highlighted')

where the same CSS selector would look like:

div.highlighted

Since WebDriver doesn’t use the same element type/attribute API and just uses findElement with a By selector, CSS selectors make the most sense since they’re powerful and self-contained.

The the best thing about using CSS selectors, in my opinion, is the Chrome Dev Tools allows you to search the DOM using a CSS selector (and XPath selectors, but please don’t use XPath), using Command/Control & F:

chrome css selectors
Using CSS selectors to find elements in Chrome Dev Tools

So you can ‘test’ your CSS in a live browser window before deciding to use it in your WebDriver test.

The downside of using CSS selectors are they’re a bit less self explanatory than explicitly using by.className or by.id.

But CSS selectors are pretty powerful: especially pseudo selectors like nth-of-type and I’ve found the only thing you can’t really do in CSS is select by text value, which you probably shouldn’t be doing anyway as text values are more likely to change (since they’re copy often changed by your business) and can be localised in which case your tests won’t run across different cultures.

The most powerful usage of CSS selectors is where you add your own data attributes to elements in your application and use these to select elements: straightforward, efficient and less brittle than other approaches. For example:

a[data-e2e-value="free"]

How do you identify elements in your WebDriver automated tests?

Checking web element styles using WebDriverJs

I try to avoid incorporating any or layout/style based checks or locators into my automated end to end tests since these typically change more often leading to a higher test maintenance burden.

But I did have a circumstance recently where I wanted to check that a change I dynamically made to a page was reflected in the resultant web element’s style.

Continue reading “Checking web element styles using WebDriverJs”

Reading CSS properties using Watir-WebDriver

There was recently a question on Stack Overflow about how you read a CSS property of an element that is defined in a stylesheet using Watir-WebDriver.

It’s really quite simple:

require 'watir-webdriver'
b = Watir::Browser.start 'minesweeper.github.com'
puts b.div(:id => 'g1minesRemaining100s').style 'background-image'