link 的水豚选择器

Capybara Selector for a link

我有以下代码 HTML,我不确定是否可以在水豚中为 "find" 构建一个选择器来获取我需要的元素。我在 rails 项目中将水豚用于黄瓜。 (生成HTML)

<tbody>
  <tr>
    <td>Heine</td>
    <td><a href="/customers/1">Show</a></td>
    <td><a href="/customers/1/edit">Edit</a></td>
    <td><a data-confirm="Are you sure?" rel="nofollow" data-method="delete" href="/customers/1">Destroy</a></td>
  </tr>
  <tr>
    <td>IKEA</td>
    <td><a href="/customers/2">Show</a></td>
    <td><a href="/customers/2/edit">Edit</a></td>
    <td><a data-confirm="Are you sure?" rel="nofollow" data-method="delete" href="/customers/2">Destroy</a></td>
  </tr>
  <tr>
    <td>testcustomer</td>
    <td><a href="/customers/5">Show</a></td>
    <td><a href="/customers/5/edit">Edit</a></td>
    <td><a data-confirm="Are you sure?" rel="nofollow" data-method="delete" href="/customers/5">Destroy</a></td>
  </tr>

如何 "find" 第一个 td 包含 "testcutomer" 的行的 href "edit"? 谢谢。

您可以使用以下内容:

find("td", :text => /\Atestcustomer\z/).first(:xpath,"..").find("a", :text => /\AEdit\z/)

find("td", :text => /\Atestcustomer\z/) 给你 td 和文本 "testcustomer",然后你使用 first(:xpath,"..") 找到那个 td 的父级,然后你找到锚标记文本 "Edit" 使用 find("a", :text => /\AEdit\z/).

如果您使用的是 racktest 驱动程序,这可以很清楚地利用在 nokogiri css 选择器可以从同级选择器开始的事实来完成,它将在正在调用元素查找。

find(:css, 'td', text: 'testcustomer').find(:css, '~ td > a', text: 'Edit')

如果使用任何可能不允许的 "real browser" 驱动程序,因为 querySelector 的规范不允许它。在这种情况下,使用 xpath 最容易完成(请注意,这也适用于 racktest,因此是跨驱动程序兼容性的首选解决方案)和以下同级轴

find(:xpath, ".//td[text()='testcustomer']/following-sibling::td/a[text()='Edit']")