水豚 - 应用 has_xpath 的用法?在带有变量的路径上

Capybara - usage of applying has_xpath? on an apath with variable

结构如下:

<div class="parent">
  <div>
    <div class="fieldRow">...</div>
  </div>
  <div>
    <div class="fieldRow">
      <div class="CheckBox">
    </div>
  </div>
  <div>
    <div class="fieldRow">...</div>
  </div>
  <div>
    <div class="fieldRow">...</div>
  </div>
</div>

在我的脚本中,我正在为 div[@class='parent'] 下的 4 个 div 中的每一个编写一个循环,旨在单击复选框,如果有,即 members = page.all(:xpath, '//div[@class='parent'])

members.each do |a|
  if **page.has_xpath?(a).find(:xpath, "div[@class='fieldRow']/div[@class='CheckBox']")**
    a.find(:xpath, "div[@class='fieldRow']/div[@class='CheckBox']").click
  end
end

但是我找不到 has_xpath 的正确用法?使用 xpath 包括变量。 请指教?谢谢!

has_xpath? 采用 XPath 表达式(不是元素)和 returns 布尔值(true/false),基于当前范围内是否有任何元素与该表达式匹配 - http://www.rubydoc.info/gems/capybara/Capybara/Node/Matchers#has_xpath%3F-instance_method。因为它 returns true/false 你不能在它上面调用 find 。对于您发布的示例,不需要 XPath 或检查元素是否存在,只需找到所有匹配的元素并单击它们即可。像

page.all('div.parent div.fieldRow div.Checkbox').each { |cb| cb.click }

page.all('div.parent div.Checkbox').each { |cb| cb.click }

如果 fieldRow class 不是您真正需要检查的内容。

注意:这假定单击元素不会使任何其他匹配的 elements/change 页面无效。

如果您真的需要对整个 members 进行处理并在它们上循环、使用 XPath 并检查是否存在,那么它将类似于

members = page.all(:xpath, './/div[@class='parent'])
members.each do |a|
  if a.has_xpath?(:xpath, ".//div[@class='fieldRow']/div[@class='CheckBox']")
    a.find(:xpath, ".//div[@class='fieldRow']/div[@class='CheckBox']").click
  end
end

注意:XPath 表达式开头的 .// 是作用域正常工作所必需的 - 请参阅 https://github.com/teamcapybara/capybara#beware-the-xpath--trap - 这是使用 CSS 选择器没有的问题, 所以你应该尽可能选择 CSS 选择器。