3

在 Rails 4 功能规范中,使用 RSpec 3 和 Capybara,我如何断言页面中是否存在一定数量的特定标签?

我试过了:

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

但它不起作用,说:

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

此外,在功能规范中测试视图中使用的标签和类的种类是一个好主意/坏做法吗?

4

1 回答 1

6

using 的问题find在于它旨在返回单个匹配元素。要查找所有匹配的元素,然后可以计算,您需要使用all

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

但是,这种方法没有使用 Capybara 的等待/查询方法。这意味着如果元素是异步加载的,断言可能会随机失败。例如,all检查存在多少元素,元素完成加载,然后断言将失败,因为它将 0 与 2 进行比较。相反,最好使用该:count选项,它会等待指定数量的元素出现.

expect(all('section.documents .document', count: 2).count).to eq(2)

这段代码有一些冗余,断言消息会有点奇怪(因为会有异常而不是测试失败),所以最好也切换到 using have_selector

expect(page).to have_selector('section.documents .document', count: 2)
于 2014-08-27T15:08:23.737 回答