How to loop through links and click each one using Watir
I have a web page with a grid, and some columns have a开发者_高级运维 link in the column header that will sort the values by that column [by round-tripping to the server].
I want to write a single Watir test that will identify those sorting links and click each one in succession. This is a smoke test that ensures there are no runtime exceptions resulting from the sort expression.
My question is, what is the best way to (1) identify these links, and (2) click each one in succession? This is what I have so far:
$ie.table(:id, "myGrid").body(:index, 1).each do | row |
row.each do | cell |
## todo: figure out if this contains a sort link
## todo: click the link now, or save a reference for later?
end
end
I think it won't be possible to click each link inside the loop since clicking a link will trigger a page load and I believe this invalidates the other Watir Link Elements.
So, what I suggest is that you take the IDs of the links and then loop over each other doing the clicks.
For instance, I would add an specific class to those sorting links and a meaningful id too. Something along the lines of:
<a id='sortby-name' class='sorting' href='...'>Name</a>
Then you can pick them with this:
$ie.table(:id, "myGrid").body(:index, 1).each do | row |
# pick sorting links' ids
sorting_link_ids = row.links.select{|x| x.class_name == "sorting"}.map{|x| x.id}
end
And then, you do your clicking like this:
sorting_link_ids.each do |link_id|
$ie.table(:id, "myGrid").body(:index, 1).link(:id, link_id).click
end
Hope that helps!
精彩评论