Tom Tom - 4 months ago 61
Ruby Question

Iterate over array Capybara Cucumber

I'm struggling to find a solution to this.

I'm accessing a table on a webpage. After applying a specific filter, one data item in each row must contain a certain value.

I've tried to create an array out of the table data, making each row it's own index.

Once I have the index, I want to scope within this row to find the certain value I'm after.

So far, I've got the following:

results_table = all('table#clickable-rows tr')

results_table.each do |row|


within(results_table[row]) do
table_data = all('table#clickable-rows td')
expect(table_data[3]).to have_text TEXT
end
end
end


It's the iteration I'm struggling with. Does anyone have a solution to this?

Thanks

Answer

A couple of things wrong here - once you start iterating on the results_table row is the actual row element (not an index to the row), so you should not be indexing into results_table again. Also, once you've called within(element) all CSS finds will then be relative to that element so you don't need to find the table again (unless looking for a table embedded in the original table). You probably want something more like

results_table = all('table#clickable-rows tbody tr')
results_table.each do |row|
  within(row) do
    table_data = all('td') # you could also just find the third one with nth-child if you only want that one column
    expect(table_data[3]).to have_text TEXT
  end
end

end

or without using within

results_table = all('table#clickable-rows tbody tr')
results_table.each do |row|
  table_data = row.all('td')
  expect(table_data[3]).to have_text TEXT
end

One important thing to note here is that by default all doesn't wait for rows to appear, so if this is being run with a JS capable driver you probably want to use something like

results_table = all('table#clickable-rows tbody tr', minimum: 1) #you can adjust minimum if you need to wait for more rows to be on the page

to make sure the table rows have actually appeared on the page

Comments