【问题标题】:How to use rspec-retry with a Selenium Net::ReadTimeout error (Ruby)如何使用带有 Selenium Net::ReadTimeout 错误的 rspec-retry (Ruby)
【发布时间】:2016-06-05 22:17:39
【问题描述】:

谁能给我一个如何使用 rspec-retry 和 selenium-webdriver 的例子。当出现 Net::ReadTimeout 错误时,我试图让它重新尝试导航。我找到了一个示例 here,但我是 Ruby 新手,我认为我没有正确使用它。

我尝试过的。

require 'selenium-webdriver'
require 'rspec/retry'

Selenium::WebDriver::PhantomJS.path = 'phantomjs.exe'
driver = Selenium::WebDriver.for :phantomjs
driver.manage.timeouts.page_load = 300

driver.navigate.to "http://google.com"

RSpec.configure do |config|
  # show retry status in spec process
  config.verbose_retry = true
  # Try five times (retry 4 times)
  config.default_retry_count = 5
  # Only retry when Selenium raises Net::ReadTimeout
  config.exceptions_to_retry = [Net::ReadTimeout]
end

puts(driver.title)
driver.quit

【问题讨论】:

  • 测试失败时您在测试日志中看到了什么?您确定它没有重试并反复失败吗?
  • 我不知道如何让它写入测试日志,所以不,我不确定它是否正在重试和失败。
  • 也许您应该为您的问题添加更多信息。您是在使用 rspec-rails 测试 Rails 应用程序,还是在测试远程应用程序?
  • 我使用的是纯 Ruby 和上面的代码。唯一的区别是我正在导航到 100 个左右的 URL。上面的代码在 90% 的情况下都能正常工作,但随后随机崩溃并出现 Net::ReadTimeout 错误。我只是想阻止它因错误而崩溃并重新导航到 URL。当我在崩溃后重新启动代码时,它似乎可以很好地导航到相同的 URL。

标签: ruby selenium rspec


【解决方案1】:

听起来您可能根本没有使用 rspec,而只是想要 rspec-retry gem 提供的重试行为。如果是这种情况,您可以使用 ruby​​ 的救援和重试关键字来实现相同的目标。

例如,如果导航抛出 Net::ReadTimeout,以下代码将重试导航 1 次

require 'selenium-webdriver'

Selenium::WebDriver::PhantomJS.path = 'phantomjs.exe'
driver = Selenium::WebDriver.for :phantomjs
driver.manage.timeouts.page_load = 300

attempts = 0  # has to be outside the begin/rescue to avoid infinite loop
begin
  driver.navigate.to "http://google.com"
rescue Net::ReadTimeout => e
  if attempts == 0
    attempts += 1
    retry
  else
    raise
  end
end

【讨论】:

    猜你喜欢
    • 2014-12-08
    • 2018-12-12
    • 2013-11-16
    • 1970-01-01
    • 2015-02-06
    • 1970-01-01
    • 2021-07-23
    • 1970-01-01
    • 2018-08-02
    相关资源
    最近更新 更多