Automated testing and dynamic ID’s

by

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?

//select[@id='???']

That would work great if I knew the ID ahead of time.  That’s where the ‘for’ attribute comes in handy:

//label[text()='Product']/@for

That will get me the for attribute of the “Product” label.  Putting it all together, it looks like this:

//select[@id=//label[text()='Product']/@for]

Tags: , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: