Liminal Existence

Assert_before

I’m working on a Ruby Jabber client library to hide the numerous machinations and relatively steep learning curve that xmpp4r requires. It’s nearly done, and I’m writing tests (it’s an extraction from Twitter’s Jabber support). A problem I was running into was the latency involved with Jabber requests; sending a message is almost instantaneous, but always requires at least a one second sleep before the assertion, sometimes much more (roster updates can be time consuming). I started sprinkling five to ten second sleeps throughout my code, but all of a sudden my tests were taking upwards of a minute to run, and there are only five tests! Here’s a snippet that should help with all your variable-latency tests:

def assert_before(seconds, &block)
  error = nil
  begin
    Timeout::timeout(seconds) {
      begin
        yield
      rescue => e
        error = e
        sleep 0.5
        retry
      end
    }
  rescue Timeout::Error
    raise error
  end
end
use it in your tests like so:

def test_something_time_consuming_should_succeed_in_at_least_10_seconds
  assert_before 10.seconds do
    assert true, time_consuming_task()
  end
end
and as soon as your tests pass, the block will exit and continue on, completing your tests as quickly as possible.