Skip to content

Instantly share code, notes, and snippets.

@xam7247
Forked from mattwynne/gist:1228927
Last active March 31, 2021 12:59
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xam7247/290868f3c6f0f72e9b01 to your computer and use it in GitHub Desktop.
Save xam7247/290868f3c6f0f72e9b01 to your computer and use it in GitHub Desktop.
eventually helper method for making assertions against asynchronous systems
# usage:
# it "should return a result of 5" do
# eventually { long_running_thing.result.should eq(5) }
# end
module AsyncHelper
def eventually(options = {})
timeout = options[:timeout] || 2
interval = options[:interval] || 0.1
time_limit = Time.now + timeout
loop do
begin
return if yield
rescue RSpec::Expectations::ExpectationNotMetError, StandardError => error
end
raise error if Time.now >= time_limit
sleep interval
end
end
end
# Can we put this into RSpec somewhere?
@johnam
Copy link

johnam commented Apr 28, 2016

Hi, it looks like this might need 'return if error.nil?' on line 17 to support:

expect {}.to_not be_blank

which returns false, whereas:

expect ().to be_present

returns true

  loop do
    begin
      yield
    rescue RSpec::Expectations::ExpectationNotMetError, StandardError => error
    end

    return if error.nil?
    raise error if Time.now >= time_limit
    sleep interval
  end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment