ruby - 如何使用 Capybara/Ruby 测试与页面上相同正则表达式匹配的多个字符串实例

标签 ruby selenium testing cucumber capybara

尝试测试一个包含 3 个房屋价格的页面。每个房价可能低至 10,000 美元,高至 1,000,000 美元,因此我编写了一个正则表达式来 try catch 数字的任何可能迭代:

\$[\d]{0,1},{0,1}[\d]{2,3},{0,1}[\d]{0,3}

我遇到的问题是我无法弄清楚如何正确构成 Capybara 表达式来验证是否有 3 次迭代。这里的第一次尝试:

Then(/^I should see (\d+) listings which contain the price in the correct format$/) do |times|
 expect(@page.price).to have_text("\$[\d]{0,1},{0,1}[\d]{2,3},{0,1}[\d]{0,3}", :count => times)
end

... 出现此错误:

Then I should see 3 listings which contain the price in the correct format
# features/step_definitions/feature_format.rb:6
Unused parameters passed to Capybara::Queries::SelectorQuery : ["$[d]{0,1},{0,1}[d]{2,3},{0,1}[d]{0,3}"]
Unused parameters passed to Capybara::Queries::SelectorQuery : ["$[d]{0,1},{0,1}[d]{2,3},{0,1}[d]{0,3}"]
Unused parameters passed to Capybara::Queries::SelectorQuery : ["$[d]{0,1},{0,1}[d]{2,3},{0,1}[d]{0,3}"]

第二次尝试:

Then(/^I should see (\d+) listings which contain the price in the correct format$/) do |times|
 for i in 1..times.to_i do
  expect(@page.price).to assert_text("\$[\d]{0,1},{0,1}[\d]{2,3},{0,1}[\d]{0,3}")
  end
 end

... 出现此错误:

Then I should see 3 listings which contain the price in the correct format               # features/step_definitions/feature_format.rb:6
      Ambiguous match, found 3 elements matching css "div.psfm-hf-ft-price" (Capybara::Ambiguous)

有人知道这里出了什么问题吗?

最佳答案

要使用正则表达式,您需要传递正则表达式而不是字符串。因此,检查页面是否与您的正则表达式匹配 3 次

expect(page).to have_text(/\$[\d]{0,1},{0,1}[\d]{2,3},{0,1}[\d]{0,3}/, count: 3)

如果 @page.price 指的是包含所有 3 个价格的页面片段,那么它将是

expect(@page.price).to have_text(/\$[\d]{0,1},{0,1}[\d]{2,3},{0,1}[\d]{0,3}/, count: 3)

然而,从“模棱两可的错误”来看,我猜测您的@page.price 选择器可能实际上选择了一个只有一个价格的元素?如果是这样的话,你想要更像的东西

expect(page).to have_css('div.psfm-hf-ft-price', text: /\$[\d]{0,1},{0,1}[\d]{2,3},{0,1}[\d]{0,3}/, count: 3)

这将检查页面是否有 3 个元素与给定的 css 选择器匹配,每个元素的内容都与正则表达式匹配

关于ruby - 如何使用 Capybara/Ruby 测试与页面上相同正则表达式匹配的多个字符串实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38881895/

相关文章:

ruby-on-rails - 通过 SendGrid 使用 Ruby on Rails 发送带附件的电子邮件

ruby-on-rails - rails 5 : can't order after group and count

python - xpath 之间的层次结构/依赖关系

selenium - 使用 Protractor 定位链接的最佳方法

轨道上的 ruby 。调度.fcgi 。 dependencies.rb :251:in `require' : cannot load such file -- fcgi (LoadError)

jquery - sprockets::StaticPages#home 中未找到文件

java - 我想在 java 中的 Selenium 中创建一个可以返回 List<WebElement> 的方法,我该怎么做?

javascript - Protractor map 函数返回未定义

python - 如何测试 POST 请求的 URL 参数?

testing - 移动和平板设备测试