From e41c757394c8683ff16f281d3dedad5e3d0bf62a Mon Sep 17 00:00:00 2001 From: Lenny Marks Date: Thu, 31 Dec 2009 13:56:23 -0500 Subject: [PATCH] Provides timeout similar to standard library Timeout, but avoids threads Capybara::WaitUntil - should return result of yield if it returns true value within timeout - should keep trying within timeout - should raise Capybara::TimeoutError if block fails to return true within timeout --- lib/capybara/wait_until.rb | 23 +++++++++++++++++++++++ spec/wait_until_spec.rb | 28 ++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+) create mode 100644 lib/capybara/wait_until.rb create mode 100644 spec/wait_until_spec.rb diff --git a/lib/capybara/wait_until.rb b/lib/capybara/wait_until.rb new file mode 100644 index 00000000..b547b9a1 --- /dev/null +++ b/lib/capybara/wait_until.rb @@ -0,0 +1,23 @@ +module Capybara + #Provides timeout similar to standard library Timeout, but avoids threads + class WaitUntil + + class << self + + def timeout(seconds = 1, &block) + start_time = Time.now + + result = nil + + until result + return result if result = yield + + if (Time.now - start_time) > seconds + raise TimeoutError + end + end + end + + end + end +end \ No newline at end of file diff --git a/spec/wait_until_spec.rb b/spec/wait_until_spec.rb new file mode 100644 index 00000000..eaa66d3c --- /dev/null +++ b/spec/wait_until_spec.rb @@ -0,0 +1,28 @@ +require File.expand_path('spec_helper', File.dirname(__FILE__)) + +require 'capybara' +require 'capybara/wait_until' + +module Capybara + + describe WaitUntil do + + it "should return result of yield if it returns true value within timeout" do + WaitUntil.timeout { "hello" }.should == "hello" + end + + it "should keep trying within timeout" do + count = 0 + WaitUntil.timeout { count += 1; count == 5 ? count : nil }.should == 5 + end + + it "should raise Capybara::TimeoutError if block fails to return true within timeout" do + running do + WaitUntil.timeout(0.1) { false } + end.should raise_error(::Capybara::TimeoutError) + end + + end + +end + \ No newline at end of file