How to check how many specific HTML elements are in a page using RSpec?
Asked Answered
R

1

5

In Rails 4 feature spec, using RSpec 3 and Capybara, how do I assert if a certain number of specific tags are present in a page?

I tried:

expect(find('section.documents .document').count).to eq(2)

But it doesn't work, saying:

Ambiguous match, found 2 elements matching css "section.documents .document"

Also, is it a good idea/bad practice to test in a feature spec something so specific as the kind of tags and classes used in the view?

Recept answered 27/8, 2014 at 13:0 Comment(0)
B
10

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)
Boult answered 27/8, 2014 at 15:8 Comment(1)
still valid and useful. couldn't figure out what to search for to find this in the docsBoigie

© 2022 - 2024 — McMap. All rights reserved.