在 rspec after(:suite) 中访问测试结果

Nic*_*k M 5 ruby rspec ruby-on-rails

目前,我在日志文件中收集了数千个 rspec 示例的输出,当出现故障时,我会解析输出并发出各种通知。

我想摆脱这个旧代码并以更文明的方式进行,例如,在 after(:suite) 块中,如果我可以访问失败的示例数组,那么我可以发送通知。

那么如何获取在 after(:suite) 块中失败的示例数组呢?

kwe*_*rle 1

啊。我讨厌 rspec 让这变得不那么容易/明显。这不是您所要求的,但它是一个明显的框架:

RSpec.configure do |config|
  ...
  config.around(:each) do |example|
    example.run # travel_to gets undone once we're back here - as opposed to around(:each)
  ensure
    RspecExecutiontimeRecorder.record(example)
  end

  config.after(:suite) do
    RspecExecutiontimeRecorder.report
  end
  ...
end

Run Code Online (Sandbox Code Playgroud)
class RspecExecutiontimeRecorder
  include Singleton

  Record = Struct.new(:full_description, :file_path, :location, :duration)

  class << self
    def record(example)
      instance.record(example)
    end

    def report
      instance.report
    end
  end

  def initialize
    @records = []
  end

  def record(example)
    # Because this callback is part of the example, we don't have an end/run time - so we make it up
    duration = Time.now - example.metadata[:execution_result].started_at
    metadata = example.metadata
    @records << Record.new(metadata[:full_description], metadata[:file_path], metadata[:location], duration)
  end

  def report
    pp @records
  end
end
Run Code Online (Sandbox Code Playgroud)

您可以只记录每个元数据,然后在最后解析它,但也许这会变成大量数据?我只对小计时位感兴趣,所以这就是我存储的全部内容。