occasionally useful ruby, ubuntu, etc


Time matcher for RSpec2

I've found myself reusing this matcher a bit for time-sensitive tests, so I thought I'd share it. It allows you to verify that a block took a certain amount of time to execute.


Drop that into a file "spec/spec_custom_matchers.rb", then in your spec_helper.rb file add

require "spec_custom_matchers"
RSpec.configure do |config|
    config.include CustomMatchers

Usage looks like this:

lambda { something_slow }.should take_between(1, 3)
lambda { something_slow }.should take_between(1, 3).seconds
lambda { something_slow }.should take_between(1).and(3)
lambda { something_slow }.should take_between(1).and(3).seconds
# if you have the ActiveSupport gem active
lambda { something_slow }.should take_between(1.second, 3.seconds)
lambda { something_slow }.should take_between(1.second).and(3.seconds)

Now, I know what you're thinking -- "you can't measure performance like this! Everyone's hardware is different!". And you're absolutely right. This isn't for testing performance -- it's for testing timing. Slightly different. Suppose I'm writing a caching library (which I may be :) ), and one of the "service calls" in a mock class that this cache library is testing simply does "sleep 0.1". If I call this "service call" twice I'd expect it to run almost as fast as running it once. So I might test that it takes between 0.1 and 0.19 seconds, to ensure that it's actually getting cached. You can be more aggressive and say "between 0.1 and 0.11 seconds", but if you're not careful you will end up testing people's hardware.

If you want to extend this example, it should be trivial to do so -- adding `takes_at_least` and `takes_at_most` matchers, for instance.

Filed under: ruby Leave a comment
Comments (0) Trackbacks (0)

No comments yet.

Leave a comment

No trackbacks yet.