Skip to content

Instantly share code, notes, and snippets.

@jamesmartin
Created February 22, 2011 11:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamesmartin/838520 to your computer and use it in GitHub Desktop.
Save jamesmartin/838520 to your computer and use it in GitHub Desktop.
Stubbing sleep
# example borrowed from Capybara.timeout
class Sleepy
def self.do_this(seconds = 1, &block)
start_time = Time.now
result = nil
until result
return result if result = yield
if (seconds - (Time.now - start_time)) <= 0
raise "Timeout!"
end
sleep(0.5)
end
end
end
describe "sleepy" do
before do
Sleepy.stub!(:sleep)
end
it "should return the value of the block if the block returns a truthy value" do
Sleepy.do_this { "hello" }.should == "hello"
end
it "should retry the block until the value is truthy" do
count = 0
Sleepy.do_this { count +=1; count == 5 ? count : nil }.should == 5
end
it "should raise an error if the block doesn't return truthy inside the timeout" do
lambda do
Sleepy.do_this(10) { false }
end.should raise_error
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment