尝试测试一个包含 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/