今天我正在努力加快我的测试套件。我的应用程序基本上是系统之间的大型集成器,所以我的大多数测试都使用这样的 Savon 模拟
RSpec.describe MyClass do
describe 'a function which sends a SOAP request'do
before do
savon.mock!
savon.expects(action).returns(File.read("spec/fixtures/somefile.xml"))
end
after { savon.unmock! }
it 'checks something'
it 'checks something else'
it 'checks something more'
it 'checks something different'
end
end
显然,这些测试中的大多数在加载文件时都非常慢。此外,有时这些模拟位于嵌套上下文中,以便组合多个共享示例,从而增加负载量。为了加快其中一些测试的速度,我试图减少将它们移动到before
块之外的文件加载数量。喜欢这个
RSpec.describe MyClass do
describe 'a function which sends a SOAP request'do
the_file = File.read("spec/fixtures/somefile.xml")
before do
savon.mock!
savon.expects(action).returns(the_file)
end
after { savon.unmock! }
it 'checks something'
it 'checks something else'
it 'checks something more'
it 'checks something different'
end
end
事实上,速度不会改变;我有 96 个带有多个、嵌套上下文和检查的测试块,我什至没有获得 0.01 秒。所以我的问题是:
- 我以为
before
块为每个它加载文件,是吗右? - Rspec 或 Savon 是否有某种缓存?
- 如何跟踪我实际加载示例文件的次数?
谢谢!
也许您应该查看钩子顺序并指定更适合您的内容,例如before (:suite)
或before (:context)
。根据您使用的那个,它将被执行
https://relishapp.com/rspec/rspec-core/docs/hooks/before-and-after-hooks
let(:the_file) { File.read("spec/fixtures/somefile.xml") }
将解决您的问题,因为 let 是惰性的计算