Note - The original article references
As we already mentioned in our previous posts CSS Selectors in Selenium Demystified and Intermediate CSS Selectors in Selenium, CSS is a selection strategy that is easier to read, simple, and generally less brittle than
For those wondering, a Pseudo-class is a way to identify an element only when it is in a special state. For example,
THE FOCUS PSEUDO-CLASS
The focus pseudo-class allows you to select the element that has focus -- the one with the blinking cursor to type into. Using it can verify that the javascript fired and a specific element has focus. Take for a moment this sample code:
What is your name?
<input id="unpredictable1234" type="text"/><BR/>
What is your quest?
<input id="also_unpredictable1234" type="text"/><BR/>
The ID’s here change every refresh and are not predictable. Perhaps they contain the order ID or user ID or some other unique element that means something to the back-end server. A few things we do know: When the page loads, nothing should have focus. When the user presses tab, the first input should have focus.
css=input:focus
CHECKING PAGE LOAD FOR NO FOCUS
Here’s the ruby code to make sure no element has
#No element has focus
found = false
begin
element = @driver.find_element :css, 'input:focus'
found = true
rescue Selenium::WebDriver::Error::NoSuchElementError
found = false
end
TAB AND FIND FOCUS
And the code to send a tab to the page, setting the focus on the first input. The code then gets the selected element, types “Hello WebDriver!” into it, and asserts the text is
@driver.action.send_keys(:tab).perform
element = @driver.find_element :css, 'input:focus'
sleep(3)
element.send_keys "Hello WebDriver!"
assert_equal(element.attribute('value'),"Hello WebDriver!")
The entire program, including the sample code, is available in Github as css_focus.rb and sample.html.
Did you find this useful? Are you still fighting with
Interested in learning how to use Selenium for your automated testing? Check out Sauce Labs Selenium courses.