Search code examples
watir

Loop in table with Watir


Stuck with watir trying to create a loop to click in all the links included in a table. Currently the table has this format:

<table id="test">
  <tbody><tr>
    <th>Firstname</th>
    <th>Lastname</th>
    <th>Link</th>
  </tr>
  <tr>
    <td>Jill</td>
    <td>Smith</td>
    <td><a href="http://facebook.com">http://facebook.com</a></td>
  </tr>
  <tr>
    <td>Eve</td>
    <td>Jackson</td>
    <td><a href="http://google.com">http://google.com</a></td>
  </tr>
</tbody></table>

And my current attempt looks like:

browser.table(:id => "test").rows do |tr|
  tr.each do |td|
    td.links.click
  end
end

This code above does nothing in the browser & neither returns something in the terminal (no errors, no outputs).

Also tried a different approach using columns:

columns = browser.table(:id => "test").strings.transpose

browser.columns.each do |t|
  t.click
  browser.back
end

That outputs this error: jsfiddle.rb:24:in <main>': undefined methodcolumns' for # (NoMethodError)


Solution

  • This should work to click on each link in the table:

    my_table = browser.table(:id, 'test')
    table_links = my_table.links.map(&:text)
    table_links.each do |link_text|
      my_table.link(:text, link_text).click
      browser.back
    end
    

    Largely based on Justin Ko's answer here.