如何查找 Rspec 中每个测试用例所花费的时间

问题描述 投票:0回答:4

我在我的项目中使用 Rspec,我想打印每个测试用例所花费的时间,Rspec 有什么方法提供任何预构建函数吗?我可以通过

example.execution_result.started_at
获取测试用例的开始时间,但我不知道如何获取测试用例的结束时间,如果我可以获取结束时间,那么我可以从开始时间减去结束时间来获取时间每个测试用例的持续时间。在这个地方有人帮助我吗?我写了这段代码

around(:each) do |example|
  startTime=Time.now
  var=example.run
  puts var
  endTime=Time.now
  duration=endTime-startTime
  puts "Time Taken->#{duration.to_f/60.to_f}"
end

但我坚信 Rspec 必须提供一些预定义的方法来返回每个测试用例的持续时间,你有人知道吗?

ruby rspec capybara watir
4个回答
10
投票

RSpec 有一个 example_status_persistence_file_path 配置,可生成一个文件,其中包含每个单独测试的运行时间。

例如,给出以下 RSpec 配置/示例:

require 'rspec/autorun'

# Enable the reporting
RSpec.configure do |c|
  c.example_status_persistence_file_path  = 'some_file.txt'
end

# Run some tests
RSpec.describe 'some thing' do
  it 'does stuff' do
    sleep(3)
  end

  it 'does more stuff' do
    sleep(2)
  end
end

生成每个示例的状态和运行时间的报告:

示例_id |状态 |运行时 |
---------------- | ------ | ------------ |
my_spec.rb[1:1] |通过 | 3.02 秒 |
my_spec.rb[1:2] |通过 | 2.01 秒 |

4
投票

如果您想要更多详细信息和/或想要控制格式,您可以创建自定义格式化程序。

例如,给定以下规格:

RSpec.describe 'some thing' do
  it 'does stuff' do
    sleep(3)
    raise('some error')
  end

  it 'does more stuff' do
    sleep(2)
  end
end

输出 - 文本

我们可以添加自定义格式化程序来输出完整的测试描述、状态、运行时间和异常:

class ExampleFormatter < RSpec::Core::Formatters::JsonFormatter
  RSpec::Core::Formatters.register self

  def close(_notification)
    @output_hash[:examples].map do |ex|
      output.puts [ex[:full_description], ex[:status], ex[:run_time], ex[:exception]].join(' | ')
    end
  end
end

RSpec.configure do |c|
  c.formatter = ExampleFormatter
end

这给了我们:

有些事情确实有用 |失败 | 3.010178 | {:class=>"RuntimeError", :message=>"some error", :backtrace=>["my_spec.rb:21:in `block... (例如被截断)
有些事情可以做更多的事情|通过 | 2.019578 |

可以修改输出以添加标题、具有更好的格式等。

输出 - CSV

可以修改格式化程序以输出到 CSV:

require 'csv'

class ExampleFormatter < RSpec::Core::Formatters::JsonFormatter
  RSpec::Core::Formatters.register self

  def close(_notification)
    with_headers = {write_headers: true, headers: ['Example', 'Status', 'Run Time', 'Exception']}
    CSV.open(output.path, 'w', with_headers) do |csv|
      @output_hash[:examples].map do |ex|
        csv << [ex[:full_description], ex[:status], ex[:run_time], ex[:exception]]
      end
    end
  end
end

RSpec.configure do |c|
  c.add_formatter(ExampleFormatter, 'my_spec_log.csv')
end

这给出了:

示例、状态、运行时间、异常
有些事情确实发生了,失败,3.020176,“{:class =>”“RuntimeError””,:message =>“”一些错误“”,:backtrace => [“”my_spec.rb:25:在`块.. .(截断的示例)”
有些事情做了更多的事情,通过,2.020113,

2
投票

每个示例都会获得一个 ExecutionResult 对象,该对象具有

run_time
方法,因此
example.execution_result.run_time
应该能够满足您的要求


0
投票

spec/rails_helper.rb
文件添加一行:

RSpec.configure do |config|
  config.profile_examples = true
end

rspec
运行完成后会显示总运行时间(以及每次测试的时间)

© www.soinside.com 2019 - 2024. All rights reserved.