Skip to content

Instantly share code, notes, and snippets.

@costa
Last active June 25, 2025 12:00
Show Gist options
  • Select an option

  • Save costa/4708b8121d46d61779a0ff6b97a77963 to your computer and use it in GitHub Desktop.

Select an option

Save costa/4708b8121d46d61779a0ff6b97a77963 to your computer and use it in GitHub Desktop.
expect_in_time (a simple "macro" for your simple RSpec polling and timing-out needs)
# Polling expectation blocks with total timeouts
# NOTE the `expect`s go in the block, e.g. `expect_in_time(3) { expect(q.pop).to eq 'fin' }`
# NOTE beware of polling busy wait, insert `sleep`s in the block as needed
require 'timeout'
def expect_in_time(sec, &blk)
errors = []
begin
Timeout.timeout sec do
begin
yield
rescue RSpec::Expectations::ExpectationNotMetError
errors << $!
retry
end
end
rescue Timeout::Error
raise if errors.empty?
raise errors[0] if errors.length == 1
raise "Time is up (#{sec}s) and here are the expectations failed: #{errors}"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment