关闭 Capybara::ElementNotFound / 避免嵌套救援

Switch off Capybara::ElementNotFound / avoid nested rescue

我对在大量集成测试中共享的方法有疑问。

问题是,我需要找到两个按钮之一,到目前为止,我只想出了以下笨拙的语法来避免 Capybara 的 ElementNotFound 错误:

new_button = begin
      find(".button_one")
    rescue Capybara::ElementNotFound
      begin
        find('.button_two')
      rescue Capybara::ElementNotFound
        raise Capybara::ElementNotFound, "Missing Button"
      end
    end
new_button.click

这按预期工作:如果找不到第一个按钮,则找到第二个按钮,然后单击它们。如果两者都不存在,则会引发错误。

尽管如此,我真的不喜欢嵌套 rescues 并且想整理一下。

感觉应该存在的最简单的解决方案,虽然我没有在任何地方找到这个:有谁知道是否有 return [=15] 的选项=] 在 Capybara 的 find 方法中,而不是引发异常?

例如下面的伪代码...

new_button = find('.button_one', allow_nil: true) || find('.button_two', allow_nil: true)
new_button ? new_button.click : raise(Capybara::ElementNotFound, "Missing Button")

...将是完美的。

否则,关于如何最好地挽救这两个错误并避免可怕的嵌套挽救有什么建议吗?


脚注:此代码存在于一个大型现有结构中,该结构以前在不应该存在的地方运行良好。修复另一个问题导致了这个问题,这个问题在整个套件中被广泛使用。我很乐意调整调用并使用正确的元素(因此完全避免这种情况),尽管这将是当天晚些时候的一个大项目。

我不熟悉 Ruby,所以我将 link 留给 Ruby docu and Capybara docu。这个想法是使用 find_elements 而不是 find_element。为什么?如果没有找到元素,find_elements 不会抛出任何异常。伪代码是这样的:

new_button = find_elements('.button_one').size() > 0 ? find('.button_one') || find('.button_two')

而且您不再需要处理异常。

尝试使用 x 路径 //button[contains(@class,'button_one') 或 contains(@class, 'button_two'] 如下所示,

new_button = begin
        find(:xpath, "//button[contains(@class,'button_one') or contains(@class, 'button_two']")
       rescue Capybara::ElementNotFound
        raise Capybara::ElementNotFound, "Missing Button"
      end

new_button.click

如果页面上只有一个按钮,最简单的解决方案是使用 CSS 逗号

同时查找两个按钮
find(".button_one, .button_two").click

如果两个按钮有可能同时出现在页面上,那么这会给您带来歧义匹配错误,在这种情况下您可以执行类似

的操作
find(".button_one, .button_two", match: :first).click

all(".button_one, .button_two")[0].click

也可以使用 Capybara 提供的谓词 has_css?/has_xpath?/etc 检查元素是否存在而不引发异常。这会给出类似

的代码
if page.has_css?(".button_one")
  find(".button_one")
else
  find(".button_two")
end.click

但在这种情况下,使用 CSS 逗号肯定是更好的解决方案。