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

In RSpec, how to determine the time each spec file takes to run?

背景:我项目的持续集成构建 运行s RSpec 并行 运行s。规范按规范文件跨并行 运行 分区。这意味着长规范文件支配测试套件 运行 时间。所以我想知道每个规范文件花费 运行 的时间(不仅仅是每个示例花费 运行 的时间)。

如何让 RSpec 告诉我每个规范文件到 运行 所需的时间? RSpec 的几个股票格式化程序告诉我每个示例花费的时间 运行,但他们没有对每个规范的时间求和。

我正在使用 RSpec 3.2.

我通过编写自己的 RSpec 格式化程序满足了这一需求。将以下 class 放入 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