Last active
June 25, 2025 12:00
-
-
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)
This file contains hidden or 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
| # 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