XPath support is indispensable for any serious web test automation tool because xpath expressions allow to precisely select nearly everything in an HTML page using a concise syntax.
Last week I had again a case showing the power of XPath. Colleagues had to write a WebTest script that should (among other steps) change the value of a select like this one:
(this blog doesn’t allow to “display” this select field it as it would normally appear, but you have surely enough HTML knowledge to understand it)
No assumption could be made on the current value of the select, the test had just to select an other valid option (meaning not the first one).
The first approach could be to read the index of the selected option, increment it, perform a modulo operation and avoid the first option. More pragmatic would be to take the second one (here “English”) if it is not already selected and the 3rd one (here “French”) if “English” was selected.
These solutions work but require some logic that can only be expressed in a script.
More elegant solution with xpath
In fact you can simply formulate the test specification with an XPath like this one:
//select[@name='mySelect']/option[text() and . != ../option[@selected]]
This XPath just selects all the options of select field
mySelect that have a “content” (i.e. not the first, empty one) and that are not currently selected.
setSelectField step takes automatically the first option when the xpath evaluation returns more than one result. For other test tools, you may need to select explicitly the first option like this
(//select[@name='mySelect']/option[text() and . != ../option[@selected]])