在RSpec中,如何确定每个spec文件运行的时间?

时间:2015-05-21 13:22:44

标签: ruby rspec

背景:我的项目的持续集成构建在几个并行运行中运行RSpec。规范通过spec文件在并行运行中进行分区。这意味着长规范文件在测试套件运行时占主导地位。所以我想知道每个spec文件运行的时间(不仅仅是每个例子运行的时间)。

如何让RSpec告诉我每个spec文件运行的时间? RSpec的几个库存格式化器告诉我每个示例运行的时间,但它们并没有为每个规范总结时间。

我正在使用RSpec 3.2。

1 个答案:

答案 0 :(得分:0)

我通过编写自己的RSpec格式化器来解决这个问题。将以下类放在spec / support中,确保它是必需的,然后像这样运行rspec:

rspec --format SpecTimeFormatter --out spec-times.txt

class SpecTimeFormatter < RSpec::Core::Formatters::BaseFormatter
  RSpec::Core::Formatters.register self, :example_started, :stop

  def initialize(output)
    @output = output
    @times = []
  end

  def example_started(notification)
    current_spec = notification.example.file_path
    if current_spec != @current_spec
      if @current_spec_start_time
        save_current_spec_time
      end
      @current_spec = current_spec
      @current_spec_start_time = Time.now
    end
  end

  def stop(_notification)
    save_current_spec_time
    @times.
      sort_by { |_spec, time| -time }.
      each { |spec, time| @output << "#{'%4d' % time} seconds #{spec}\n" }
  end

  private

  def save_current_spec_time
    @times << [@current_spec, (Time.now - @current_spec_start_time).to_i]
  end

end