如何在spec_helper.rb中指定自定义格式化程序?

问题描述:

我正在使用需要很长时间运行的Rspec测试来开发Rails项目。为了弄清楚哪些是采取了这么多时间,我想我会做出RSpec的自定义格式,并把它打印出每个例子中的持续时间:如何在spec_helper.rb中指定自定义格式化程序?

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) 

我如何可以作为一个符号我的自定义格式?

这不完全是答案,但是,您知道可以使用--profile标志运行RSpec来做到这一点,对吧? :)

+0

这一切都被拉开帷幕我们的CI服务器通过运行RSpec :: Core :: RakeTask.new(:our_spec)的Rake任务,所以我认为配置是设置格式化程序的最佳位置。 –

+0

好吧,您可以编辑您的项目.rspec文件并在里面添加--profile标志。 – DuoSRX

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' 

您可以按照下面的格式复制到您的spec目录并运行RSpec的命令:

rspec spec/ -f TimestampFormatter