是否有更简单的方法来编写以下黄瓜测试?

时间:2011-09-28 09:53:09

标签: ruby regex cucumber webrat

我正在使用cucmber测试一个php应用程序,它实际上运行得很好。

我有一个cucmber功能,它使用以下步骤检查页面中是否存在链接:

Then /^I should see a link that contains "(.+)"$/ do |link|
    assert !!(response_body =~ 
      /<a ([\w\.]*="[\w\.]*" )*href="(http:\/\/)?([\w\.\/]*)?(#{link})/m), response_body
end

现在,这有效,但它很丑陋而复杂。

最初我尝试使用xpath的东西:

response_body.should have_xpath("//a[@href=\"#{link}\"]")

但是,如果我检查“blah.com”的链接,那么它将与“http://blah.com”不匹配 - 哪种方式违背了测试的整个目的。因此我切换到正则表达式。

那么有一种更简单的方法来编写不依赖于复杂正则表达式的测试吗?

干杯。

编辑: 经过大量的拉毛......我确实找到了一种不那么混乱的方式来查找我的页面上的图像:

response_body.should include(image)

图像字符串设置为'myimage.png'之类的东西 - 当然,如果实际文本'myimage.png'在页面而不是图像上,这将会中断。 肯定有更好的办法。我正在考虑Hpricot,看看我是否可以解析html并提取我想要测试的属性,然后使用正则表达式进行测试,但所有这些都显得如此......臃肿。

2 个答案:

答案 0 :(得分:1)

这样的事情应该有效:

response_body.should have_css("a[href*='#{link}']")

详情请见: http://www.w3.org/TR/css3-selectors/#attribute-substrings

编辑: 看起来webrat的等效方法是has_selector,所以:

response_body.should have_selector("a[href*='#{link}']")

答案 1 :(得分:0)

Then /^I should see the image "(.+)"$/ do |image|    
  response_body.should have_selector("img[src*='#{image}']")
end

Then /^I should see a link that contains "(.+)"$/ do |link|    
  response_body.should have_selector("a[href*='#{link}']")
end

感谢AlistairH - 您的建议有效! :)

我仍然不明白为什么用css选择器语法搜索 html 但也许这只是一个设计选择他们写的人因为它看起来比正则表达式更容易......?我不知道。