Last Updated: February 25, 2016
·
2.395K
· we4tech

Measure Spec Execution Time

You can easily measure your spec execution time just by adding the following codes.
Update your spec_helper.rb with the following changes -

SPEC_STATS        = {}
SPEC_STAT_ENABLED = 'true' == ENV['SPEC_STAT']

RSpec.configure do |config|
  config.before(:each) do
    @__started = Time.now if SPEC_STAT_ENABLED
  end

  config.after(:each) do
    if SPEC_STAT_ENABLED
      SPEC_STATS[@example.full_description] = (Time.now.to_f - @__started.to_f).to_f
    end
  end

  config.after(:suite) do
    if SPEC_STAT_ENABLED
      puts "-----------------------"
      puts "Spec Performance Report"
      puts "-----------------------"

      SPEC_STATS.sort { |a, b| a.last <=> b.last }.each do |spec, took|
        puts "#{took.round(3).to_s.colorize(:yellow)} secs - #{(spec + "").colorize(:green)}"
      end
  end
end

Now hit the

SPEC_STAT=true rspec

Thats it.