如何在spec_helper.rb中指定自定义格式化程序?
我正在开发一个 Rails 项目,其中的 Rspec 测试需要很长时间才能运行。为了弄清楚哪些花费了这么多时间,我想我应该为 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)
如何使自定义格式化程序可用作符号?
I'm working on a Rails project with Rspec tests that take very long to run. In order to figure out which ones are taking so much time I figured I'd make a custom formatter for RSpec and have it print out the duration of each example:
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
And in my spec_helper.rb I tried the following:
RSpec.configure do |config|
config.formatter = :timestamp
end
But I end up getting the following error when running rspec:
configuration.rb:217:in `formatter=': Formatter 'timestamp' unknown - maybe you meant 'documentation' or 'progress'?. (ArgumentError)
How do I make my custom formatter available as a symbol?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是错误的。对于自定义格式化程序,您需要根据您的情况指定完整的类名
This is wrong. For custom formatters you need to specify full class name, in your case
这并不完全是答案,但是您知道可以使用 --profile 标志运行 RSpec 来做到这一点,对吗? :)
This is not exactly the answer but, you know you can run RSpec with the --profile flag to do just that, right ? :)
您可以将格式化程序复制到您的spec目录并运行rspec命令,如下所示:
You can copy the formatter to your spec directory and run the rspec command as following: