ruby-on-rails - capybara :如何断言给定数量的元素存在

标签 ruby-on-rails testing cucumber capybara integration-testing

我已将我的整个堆栈从基于 Rails 3.0 的项目升级到 3.1。我的规范已通过,但我的功能现在有点挑剔。我目前遇到的问题是这一步:

Then /^I should see (\d+) menu item(?:s)? within "([^"]*)"$/ do |count, selector|
  page.find(:css, selector, :count => count.to_i)
end

在功能本身,我可能会说:

Then I should see 5 menu items within "tr#menu_item_row"

我得到的信息是:

Then I should see 5 menu items within "tr#menu_item_row"                                      # features/step_definitions/admin_menu_steps.rb:1
  Ambiguous match, found 5 elements matching css "tr#menu_item_row" (Capybara::Ambiguous)
  ./features/step_definitions/admin_menu_steps.rb:2:in `/^I should see (\d+) menu item(?:s)? within "([^"]*)"$/'
  features/admin_menu.feature:30:in `Then I should see 5 menu items within "tr#menu_item_row"'

据我所知,这 5 个元素与实际找到的 5 个元素相匹配。是我写错了这段代码还是发生了重大变化?谢谢!

最佳答案

如果你想检查 5 个元素,你不应该使用 #find 作为默认值,因为 Capybara 2.0 如果发现多于或少于一个元素,此方法总是抛出异常。这是一个有意的并且(我相信)一个好的改变。

断言存在 5 个元素的适当方法是 rspec 匹配器:

expect(page).to have_css(selector, count: count.to_i)

我不推荐to set match to prefer_exact正如@fontno 所推荐的那样,在大多数情况下,如果 find 找到多个元素,您希望 Capybara 抛出异常。

关于ruby-on-rails - capybara :如何断言给定数量的元素存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17003340/

相关文章:

ruby-on-rails - .erb 、 .rhtml 和 .html.erb 之间有什么区别?

Java/Selenium WebDriver : Focus Don't skip to Else If block when the warning message matches on webpage

mysql - 将 Rails 应用程序从 postgresql 迁移到 mysql

jquery - 如何使用 Mouseenter 事件渲染 Rails Partial

python-3.x - 如何在python中测试jdbc连接?

forms - 如何在 Laravel 5 中测试表单请求规则?

typescript - 使用 typescript 的路径映射不适用于 cucumber 测试运行器

java - cucumber + Spring : How to trigger SmartLifecycle events through tests?

html - 在 Rails 中使用 Bootstrap 样式和 partials

java - MTaaS 导致资源泄漏