我在我的项目中使用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必须提供一些预定义的方法来返回每个测试用例的持续时间,您知道吗?
答案 0 :(得分:1)
每个示例都会获取一个具有run_time
方法的ExecutionResult对象,因此example.execution_result.run_time
应该可以为您提供所需的信息
答案 1 :(得分:1)
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
生成每个示例的状态和运行时间的报告:
example_id | status | run_time | --------------- | ------ | ------------ | my_spec.rb[1:1] | passed | 3.02 seconds | my_spec.rb[1:2] | passed | 2.01 seconds |
答案 2 :(得分:1)
如果您想要更多细节和/或想要控制格式,则可以创建自定义格式器。
例如,给定以下规格:
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
这给我们:
some thing does stuff | failed | 3.010178 | {:class=>"RuntimeError", :message=>"some error", :backtrace=>["my_spec.rb:21:in `block... (truncated for example) some thing does more stuff | passed | 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
哪个给:
Example,Status,Run Time,Exception some thing does stuff,failed,3.020176,"{:class=>""RuntimeError"", :message=>""some error"", :backtrace=>[""my_spec.rb:25:in `block...(truncated example)" some thing does more stuff,passed,2.020113,