bts*_*bts 2 testing tdd capybara ruby-on-rails-4 rspec3
在使用RSpec 3和Capybara的Rails 4功能规范中,如何断言页面中是否存在一定数量的特定标签?
我试过了:
expect(find('section.documents .document').count).to eq(2)
Run Code Online (Sandbox Code Playgroud)
但这是行不通的,它说:
Ambiguous match, found 2 elements matching css "section.documents .document"
Run Code Online (Sandbox Code Playgroud)
另外,在功能规范中测试某些特定的东西(例如视图中使用的标记和类)是否是个好主意/不好的做法?
使用的问题find是它旨在返回单个匹配元素。要找到所有可以计数的匹配元素,您需要使用all:
expect(all('section.documents .document').count).to eq(2)
Run Code Online (Sandbox Code Playgroud)
但是,这种方法没有利用Capybara的等待/查询方法。这意味着,如果元素异步加载,则断言可能会随机失败。例如,all检查存在多少个元素,完成加载,然后断言失败,因为它比较0到2。相反,最好使用:count选项,该选项要等到指定数量的元素出现后再进行。
expect(all('section.documents .document', count: 2).count).to eq(2)
Run Code Online (Sandbox Code Playgroud)
此代码中有一些冗余,并且断言消息会有些奇怪(因为将有异常而不是测试失败),因此最好也切换到using have_selector:
expect(page).to have_selector('section.documents .document', count: 2)
Run Code Online (Sandbox Code Playgroud)