First off, if you’ve never used the testing tools Selenium or WebTest, you should give them a try. Each of these tools is used to generate and run scripted interaction with your Web site (i.e. Web app functional testing).
As I built a regression test for a bug I found, I needed to automate selecting an option from a drop-down. Usually the test recorders handle this for me, and I give it no thought. The catch is, the ‘id’ of the select element could be different on any given test run. What I really needed was to choose a select element based on its label rather than its ‘id.’
Consider this (dynamically generated) HTML fragment:
<label for="arbitraryElementId">Product</label> <select name="productX_another_arbitrary_id" id="arbitraryElementId"> <option>foo</option> <option>fizzle</option> </select><label for="somethingElse">Qty</label> <select name="qtyX_another_arbitrary_id" id="somethingElse"> <option>10</option> <option>20</option> </select>
How can I locate the correct select element without referencing them by ID?
That would work great if I knew the ID ahead of time. That’s where the ‘for’ attribute comes in handy:
That will get me the for attribute of the “Product” label. Putting it all together, it looks like this: