我正在使用Rspec测试开发一个Rails项目,需要很长时间才能运行。为了弄清楚哪些花了这么多时间,我想我会为RSpec制作一个自定义格式化程序并打印出每个例子的持续时间:
require 'rspec/core/formatters/base_formatter'
class TimestampFormatter < RSpec::Core::Formatters::BaseFormatter
def initialize(output)
super(output)
@last_start = 0
end
def example_started(example)
super(example)
output.print "Example started: " << example.description
@last_start = Time.new
end
def example_passed(example)
super(example)
output.print "Example finished"
now = Time.new
time_diff = now - @last_start
hours,minutes,seconds,frac = Date.day_fraction_to_time(time_diff)
output.print "Time elapsed: #{hours} hours, #{minutes} minutes and #{seconds} seconds"
end
end
在我的spec_helper.rb中,我尝试了以下内容:
RSpec.configure do |config|
config.formatter = :timestamp
end
但是在运行rspec时我最终得到以下错误:
configuration.rb:217:in `formatter=': Formatter 'timestamp' unknown - maybe you meant 'documentation' or 'progress'?. (ArgumentError)
如何将自定义格式化程序用作符号?
答案 0 :(得分:4)
config.formatter = :timestamp
这是错误的。对于自定义格式化程序,您需要指定完整的类名称,在您的情况下
# if you load it manually
config.formatter = TimestampFormatter
# or if you do not want to autoload it by rspec means, but it should be in
# search path
config.formatter = 'TimestampFormatter'
答案 1 :(得分:2)
这不是答案,但是,你知道你可以使用--profile标志运行RSpec来做到这一点,对吧? :)
答案 2 :(得分:1)
您可以将格式化程序复制到spec目录并运行rspec命令,如下所示:
rspec spec/ -f TimestampFormatter