超时重试?

时间:2012-12-24 09:21:15

标签: selenium cucumber capybara

我有一个用于测试UI功能的Cucumber场景。有时候由于其中一个问题,网页需要大量的时间来回应,而且水豚会因为跟随错误而超时。

ruby-1.9.3-p327/lib/ruby/1.9.1/net/protocol.rb:146:in `rescue in rbuf_fill'
ruby-1.9.3-p327/lib/ruby/1.9.1/net/protocol.rb:140:in `rbuf_fill'
ruby-1.9.3-p327/lib/ruby/1.9.1/net/protocol.rb:122:in `readuntil'
ruby-1.9.3-p327/lib/ruby/1.9.1/net/protocol.rb:132:in `readline'
ruby-1.9.3-p327/lib/ruby/1.9.1/net/http.rb:2562:in `read_status_line'
ruby-1.9.3-p327/lib/ruby/1.9.1/net/http.rb:2551:in `read_new' 

我的问题是 -

我可以以某种方式强制Cucumber场景或Capybara分别在超时错误时重试(持续次数)整个场景或步骤吗?

2 个答案:

答案 0 :(得分:2)

也许,你可以这样做:

Around do |scenario, block|
  for i in 1..5
    begin
      block.call
      break
    rescue Timeout::Error
      next
    end
  end
end

但由于bug(It's not possible to call block several times in Around hook

,我无法弄清楚这段代码是否有效

答案 1 :(得分:1)

来自The Cucumber book

添加一个eventually method,它会一直尝试运行一段代码,直到它停止引发错误或达到时间限制为止。

以下是该方法的代码:

module AsyncSupport
  def eventually
    timeout = 2
    polling_interval = 0.1
    time_limit = Time.now + timeout
    loop do
      begin 
        yield
      rescue Exception => error
      end
      return if error.nil?
      raise error if Time.now >= time_limit sleep polling_interval
    end
  end
end
World(AsyncSupport) 

从step_definition中调用的方法如下:

Then /^the balance of my account should be (#{CAPTURE_CASH_AMOUNT})$/ do |amount|
  eventually { my_account.balance.should eq(amount) }
end