The Issue
We want to verify a CSS property (a.k.a. ‘style’) for an object (‘element’) on a web page in a Ruby Selenium Webdriver script.
A Solution
CSS properties are the HTML/DOM element attributes directly affected by the CSS style sheets loaded with the page or inline with the HTML.
A comprehensive list is shown in any of the browser dev tools. In Chrome that list is under the ‘Computed’ tab and the attributes in bold are those being set through CSS.
Our example is the ‘Categories’ button on this 3qilabs.com page. The ‘button’ is actually a div in disguise associated with a select list.
We want to validate, in Ruby using Selenium Webdriver, whether the style values we are interested in contain the values we expect. Here is a method that does this.
1 2 3 4 5 6 7 8 |
def element_style_contains?(how, what, style, expected) target = @browser.element(how.to_sym, /#{what}/).when_present if target.style(style).match(expected) true else false end end |
Parameters:
- how – a string or symbol indicating the element’s identifying attribute
- what – a string that the identifying attribute must contain.
- style – the CSS property to be checked
- expected – a string that the style value should contain.
Examples:
1 2 3 4 5 |
# Example ! element_style_contains?(:class, ‘categories_sel’, ‘font-family’, ‘muller’) # Example 2 element_style_contains?(:class, ‘categories_sel’, ‘font-size’, ‘16px’) |
Both examples will return true.
If you are looking for an exact match, as we most often are, use this very similar method.
1 2 3 4 5 6 7 8 |
def element_style_<em><strong>equals</strong></em>?(how, what, style, expected) target = @browser.element(how.to_sym, /#{what}/).when_present if target.style(style)<strong> ==</strong> expected true else false end end |
The italicized text comprises the only difference between them.
1 2 3 4 5 |
# Example 3 element_style_<em><strong>equals</strong></em>?(:class, ‘categories_sel’, ‘font-family’, ‘muller’) # Example 4 element_style_<em><strong>equals</strong></em>?(:class, ‘categories_sel’, ‘font-size’, ‘16px’) |
Example 4 returns true like example 2. Example 3 returns false because expected ‘muller’ is only part of the actual value ‘muller_regularregular’.
The Result
You now have methods, in Ruby with Selenium Webdriver, to verify the values in a DOM element’s CSS style attributes. Enjoy!