我正在使用需要很长时间才能运行的 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)
如何使我的自定义格式化程序可用作符号?
最佳答案
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'
关于ruby-on-rails - 如何在 spec_helper.rb 中指定自定义格式化程序?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7676261/