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