The HTML tag ‘label’ is very useful. The label can easily be located by its text and its referenced element by the value in its ‘for’ attribute. This makes automation of actions on the referenced element much easier and understandable to the less technical user/tester.
Of course that means that the ‘for’ attribute has to be used.
In this example
The checkbox element (id=’ dijit_form_CheckBox_0’) can be directly located by the id but if the list of boxes is changed, and a new box is inserted at the beginning of the list, that id is linked to a different data item. The checkbox itself does not contain text. Identifying text is associated with it using a label element.
The label is linked to the checkbox by its id and the checkbox attribute ‘aria-labelledby’. One can parse through the surrounding elements looking for a match in several ways.
The fastest way would be for the label element to include ‘for=’dijit_form_CheckBox_0’ which will allow more direct location of the checkbox.
a_checkbox = browser.checkbox(:id, browser.label(:text, ‘Are there Co-Borrowers?).for)
As a bonus this is also an accessibility criteria: Using labels and the ‘for’ attribute is part of most accessibility standards. See http://www.w3.org/TR/2012/NOTE-WCAG20-TECHS-20120103/H44 for thorough explanation of how to use labels.
This next way is slower and more brittle because of the index
a_checkbox = browser.label(:text, ‘Are there Co-Borrowers?).parent.checkboxes
and this even slower, more verbose, and possibly more brittle
lbl_id = browser.label(:text, ‘Are there Co-Borrowers?).id
div_id = lbl_id.gsub(/_label$/, ‘’)
a_div = browser.div(:id, an_id)
a_div.checkboxes.each do |box|
if box.attribute_value(‘aria-labelledby’) == label_id
a_checkbox = box
The moral of the story: Always use directly linked labels and use them with any element they can be linked to.