2011-10-06 89 views
3

我正在使用需要很長時間運行的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) 

我如何可以作爲一個符號我的自定義格式?

回答

2

這不完全是答案,但是,您知道可以使用--profile標誌運行RSpec來做到這一點,對吧? :)

+0

這一切都被拉開帷幕我們的CI服務器通過運行RSpec :: Core :: RakeTask.new(:our_spec)的Rake任務,所以我認爲配置是設置格式化程序的最佳位置。 –

+0

好吧,您可以編輯您的項目.rspec文件並在裏面添加--profile標誌。 – DuoSRX

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

您可以按照下面的格式複製到您的spec目錄並運行RSpec的命令:

rspec spec/ -f TimestampFormatter 
相關問題