使用nth-child水豚的模糊比赛

时间:2013-07-29 18:19:04

标签: html capybara

我正在尝试测试排序是否适用于我正在测试的应用。我添加了两个条目'a'和'b'。我想测试一下b之前出现的情况。 Html如下:

<ul id="attendee-list" class="bars">
<div>
    <li id="attendee-812202" class="bar border link attendee">
    <a class="expandable clearfix" href="#!/person/812202/">
</div>
     <div class="description">
     <p class="title">a</p>
     <p class="subtitle"></p>
     <p class="subtitle"></p>
</div>
</a>
</li>
</div>
<div>
     <li id="attendee-812206" class="bar border link attendee">
     <a class="expandable clearfix" href="#!/person/812206/">
     <div class="description">
     <p class="title">b</p>
<p class="subtitle"></p>
<p class="subtitle"></p>
</div>
</a>
</li>
</div>
</ul>

所以我尝试的是以下内容:

  find("ul.bars li:nth-child(1) a div.description p.title").should have_content("a")
  find("ul.bars li:nth-child(2) a div.description p.title").should have_content("b")

然而,我得到一个模棱两可的匹配错误。有谁知道我在这里做错了什么或者可能是另一种验证方法吗?

1 个答案:

答案 0 :(得分:35)

<强>问题

问题是li:nth-child(1)。这就是找到一个li,它是其父母的第一个孩子。由于每个li都包含在div中,因此两个li元素都是第一个子元素 - 即两个标题都由选择器ul.bars li:nth-child(1) a div.description p.title返回(因此模糊匹配)。 / p>

解决方案1 ​​ - 全部查找

我认为最简单的解决方案是使用css-selector返回所有标题,然后使用Capybara检查第一个和第二个。

# Get all titles
titles = page.all("ul.bars li a div.description p.title")

# Make sure that the first and second have the correct content
titles[0].should have_content("a")
titles[1].should have_content("b")

解决方案2 - Xpath

另一种解决方案,如果你不想得到所有(可能页面上有太多),就是试试xpath。它不是很漂亮,但你可以这样做:

page.find(:xpath, '(//ul[@class="bars"]/div/li/a/div[@class="description"]/p[@class="title"])[1]').should have_content("a")
page.find(:xpath, '(//ul[@class="bars"]/div/li/a/div[@class="description"]/p[@class="title"])[2]').should have_content("b")
相关问题