Created
February 22, 2011 11:07
-
-
Save jamesmartin/838520 to your computer and use it in GitHub Desktop.
Stubbing sleep
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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