27 March 2012

using .times in a test

When you have a selection of items you want to run the same action on, you can use .times.  .times will execute the action in the closure the specified amount of times.  For example, if you have a page with 20 checkboxes, and you want to check 8 of them and save, you could run:

8.times {
    clickCheckBox(it+1).click()
}

In the example it will execute the closure statement 8 times.

Within the closure the clickCheckBox is a reference to static content defined on the page object.  Like:
clickCheckBox {checkBox->$("#value input[value='$checkBox'")]}

A developer on my team (Ishwinder) helped me out with this.  I would have just used the typical $(#value input[value='1']) but he made it more elaborate by putting a integer here.  Then he says back in the test's closure:

(it+1).click()

Which is setting the integer value.

Of course this works in an example where the value of each checkbox is a sequential number.

When the test is run, it runs this action 8 times, incrementing the value by 1 each time, and since in this case the check box value identifiers in the html are sequential numbers, it works beautifully. 

This can be useful in other cases as well, where you want to run the actions within a closure repeatedly.  It certainly refactors a lot of code into a nice little snippet.

No comments:

Post a Comment