我正在尝试加快大型 RSpec 项目的测试。除了使用 RSpec 的 --profile
选项外,我还想打印出运行时间最长的测试文件 [1]。
在我的 spec_helper.rb
中,我将正在测试的类和总时间转储到一个文件中,但是因为我们有 spec/model
和 spec/request
目录我真的很希望能够打印当前测试的文件名 而不仅仅是类名 (described_class
),这样用户就可以在 model/foo_spec.rb
和 request/foo_spec.rb
优化时。
在 spec/spec_helper.rb
的 before
block 中,如何获取当前测试文件的文件名?
我的(经过大量修剪的)spec_helper
看起来像这样:
config.before :all do
@start_time = Time.now
end
config.after :all do |test|
timings.push({ :name => test.described_class,
:file => 'I do not know how to get this',
:duration_in_seconds => (Time.now - @start_time) })
end
config.after :suite do
timing_logfile_name = 'log/rspec_file_times.log'
timing_logfile = "#{File.dirname(__FILE__)}/../#{timing_logfile_name}"
file = File.open(timing_logfile, 'w')
timings.sort_by{ |timing| timing[:duration_in_seconds].to_f }.reverse!.each do |timing|
file.write( sprintf("%-25.25s % 9.3f seconds\n",
timing[:name], timing[:duration_in_seconds]) )
end
file.close
tell_if_verbose("Overall test times are logged in '#{timing_logfile_name}'")
end
这似乎在当前的 RSpec 元数据中不可用,但我希望更熟悉内部结构的人可以想出一种方法来公开它。谢谢, 戴夫
[1] 通常,一个包含 100 个示例的文件比来自 --profile 的单个示例产生更快的速度 - 当那个大文件的 before :each
/before 时:所有
block 都是目标,显然即使保存的 ms 也会乘以文件中的测试数。在 --profile
之外使用这种技术对我帮助很大。
最佳答案
只要你只是用它来分析你的测试以确定哪些文件需要改进,你应该能够把它扔到你的 spec_helper.rb
文件中(然后删除它).我完全理解这在生产环境中并不漂亮/干净/优雅/ Not Acceptable ,我否认我曾经写过它:)
config.before(:each) do |example|
path = example.metadata[:example_group][:file_path]
curr_path = config.instance_variable_get(:@curr_file_path)
if (curr_path.nil? || path != curr_path)
config.instance_variable_set(:@curr_file_path, path)
puts path
end
end
关于ruby-on-rails - 如何从 RSpec 获取当前测试文件名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9891028/