22 February 2012

GEB: Handling different elements with same identifier

Yesterday I had a situation where I was writing an automation script in GEB to check data in a page.  The page was created, with a table with multiple rows. Each row had a class element.  It seemed easy, until I realized, that each row was given the same class element name. 

So the table looked like this:

<td class="header">Occupation: "</td>
<td class="header">Age: "</td>

So when I tried to do this:
assert $("td.header").text() == "Occupation:"
assert $("td.header").text() == "Age:"

it would fail.  It was failing because it kept hitting the first element named "header" and wouldn't go to the second one.

I found the solution to this problem from the Book of GEB.  The way to work around this, is to use a built in GEB format.  GEB can run through elements, much like an array, by simply appending the numeric of the element in order.  0, being the first.  so in my example, Occupation would be 0, Age would be 1.

The code then looked like:
            assert $("td.header", 0).text() == "Occupation:"
            assert $("td.header", 1).text() == "Age:"

It worked perfectly.  

No comments:

Post a Comment