The problem with using find
is that it is meant to return a single matching element. To find all matching elements, which can then be counted, you need to use all
:
expect(all('section.documents .document').count).to eq(2)
However, this approach does not make use of Capybara's waiting/query methods. This means that if the elements are loaded asynchronously, the assertion may randomly fail. For example, all
checks how many elements are present, the elements finish loading and then the assertion will fail because it compares 0 to 2. Instead, it would be better to make use of the :count
option, which waits until the specified number of elements are present.
expect(all('section.documents .document', count: 2).count).to eq(2)
There is some redundancy in this code and the assertion message will be a bit strange (since there will be an exception rather than a test failure), so it would be better to also switch to using have_selector
:
expect(page).to have_selector('section.documents .document', count: 2)