Home > Mobile >  Iterating through div class in Capybara
Iterating through div class in Capybara

Time:04-19

I've got a page containing multiple elements of class div In Capybara, I want to be able to loop through and refer to the first text in the first row.

However, none of the code I've tried so far has worked. Here's what I've tried:

page.all(:css, 'div').each do |text|
    expect(text).to_have 'Goku'[0]
end

I'm trying to loop through the page and seeing if I can find the text Goku in the first column.

Here is my HTML tag

<div >Goku</div>

Expected Output: I'm expecting the first row to have text 'Goku'. My expect line should detect that the first row has Goku.

Actual output: Error for now

CodePudding user response:

First, you don't have elements of class div, you have elements of type div. Terminology matters when discussing these things since class is something different in HTML. Second, you mention first row, and first column but only show one html element which makes it very difficult to work out exactly what you're dealing with and trying to actually do.

When you use each to loop through the results of all, text is referencing a single div element. Therefore expect(text).to_have 'Goku'[0] will raise an exception if any div on the page doesn't have the letter 'G' in it (not really sure why you have the [0] there.

Really you have

page.all(:css, 'div').each do |div_element|
    expect(div_element).to_have('Goku'[0])
end

which will never pass because there are going to be hundreds (at least) of div elements on the page which don't include that text (or the letter G)

If what you're really trying to find is elements that are the first child of some other element and contain exactly the text Goku then you could do something like

page.all('* > div:first-child', exact_text: 'Goku')

to find them. If that's not what you're trying to do then please update the question to make it clearer.

  • Related