Capybara / Cucumber在Ruby中:当不再存在元素时停止搜索

时间:2016-03-28 19:41:46

标签: ruby cucumber capybara acceptance-testing

我正在测试的网站有一堆选定的过滤器(picture for context)。我循环遍历所有这些并关闭它们:

When /^each (.+) is clicked$/ do |element|
  page.all("#{element}").each do |element|
    element.click
  end
end

此代码单击关闭按钮并关闭所有打开的过滤器。我遇到的问题是,当我到达过滤器的末尾时,它会继续查看并引发此错误:

stale element reference: element is not attached to the page document
        (Session info: chrome=49.0.2623.87)
        (Driver info: chromedriver=2.20.353124 (035346203162d32c80f1dce587c8154a1efa0c3b),platform=Mac OS X 10.10.5 x86_64) (Selenium::WebDriver::Error::StaleElementReferenceError)
      ./features/step_definitions/ux_steps.rb:22:in `block (2 levels) in <top (required)>'
      ./features/step_definitions/ux_steps.rb:21:in `/^each (.+) is clicked$/'
      features/ux.feature:16:in `When each span is clicked'

HTML:

<div class="sort-block order" id="selectedFilters">
    <a id="Anti-Inflammatory_selectedfilter" href="javascript:void(0)" class="current">Anti-Inflammatory<span class="selectedFilterCross" onclick="selectedFilterFun('selectedFilterText1','Anti-Inflammatory',-1); $(this).parent('a').remove();">X</span></a>
    <a id="Cardiac_selectedfilter" href="javascript:void(0)" class="current">Cardiac<span class="selectedFilterCross" onclick="selectedFilterFun('selectedFilterText1','Cardiac',-1); $(this).parent('a').remove();">X</span></a>
    <a id="Diabetic_selectedfilter" href="javascript:void(0)" class="current">Diabetic<span class="selectedFilterCross" onclick="selectedFilterFun('selectedFilterText1','Diabetic',-1); $(this).parent('a').remove();">X</span></a>
</div>

有关如何在项目列表为空后停止搜索的任何想法?感谢所有帮助!

1 个答案:

答案 0 :(得分:1)

我认为这是因为您开始循环时页面上的元素会通过单击从页面中删除。如果是这样,您应该能够通过反复搜索可点击元素,点击找到的第一个元素并再次搜索直到找不到它来修复它:

When /^each (.+) is clicked$/ do |selector|
  while true
    element = page.first(selector)
    if element
      element.click
    else
      break
    end
  end
end

请注意,"#{string}"string相同。