[rspec-users] Performance tests using Rspec

David Chelimsky dchelimsky at gmail.com
Mon Jan 17 14:17:27 EST 2011


On Jan 16, 2011, at 8:29 PM, Evan wrote:

> 1) Know of any guides to writing performance tests using Rspec?

There's nothing built in as of yet, but you can do this pretty easily:

<code>
require 'benchmark'

RSpec::Matchers.define :take_less_than do |n|
  chain :seconds do; end
  
  match do |block|
    @elapsed = Benchmark.realtime do
      block.call
    end
    @elapsed <= n
  end

end

describe "addition" do
  it "runs fast" do
    expect do
      10000.times { 1 + 2 }
    end.to take_less_than(0.001).seconds
  end
end
</code>

> 2) Does Rspec have the capability to run specs in benchmarking or
> profiling mode similar to the way Rails has performance tests that run
> in these modes (http://guides.rubyonrails.org/
> performance_testing.html)?

There is a --profile command line switch:

  rspec spec --profile

which gives you the 10 slowest running examples, but that includes time to run all the before, after, and around hooks as well. My guess is you'd be better off with the matcher above.

HTH,
David


More information about the rspec-users mailing list