我有一些较慢的规格需要优化。此类规范的示例如下所示:
require 'rspec'
class HeavyComputation
def compute_result
sleep 1 # something compute heavy here
"very big string"
end
end
describe HeavyComputation, 'preferred style, but slow' do
subject { described_class.new.compute_result }
it { should include 'big' }
it { should match 'string' }
it { should match /very/ }
# +50 others
end
这是非常易读的,我对它总体上很满意,除了每个额外的规范都会在总运行时间上增加至少 1 秒。这是不太可接受的。
(请不要讨论HeavyComputation
类的优化,因为它超出了这个问题的范围)。
所以我不得不求助于这样的规范:
describe HeavyComputation, 'faster, but ugly' do
subject { described_class.new.compute_result }
it 'should have expected result overall' do
should include 'big'
should match 'string'
should match /very/
# +50 others
end
end
这显然在性能方面要好得多,因为运行它的时间几乎是恒定的。问题是故障很难追踪,而且阅读起来也不是很直观。
所以理想情况下,我想两者兼而有之。这些方面的东西:
describe HeavyComputation, 'what I want ideally' do
with_shared_setup_or_subject_or_something_similar_with do
shared(:result) { described_class.new.compute_result }
subject { result }
it { should include 'big' }
it { should match 'string' }
it { should match /very/ }
# +50 others
end
end
但不幸的是,我什至看不到从哪里开始实施它。它存在多个潜在问题(是否应该在共享结果上调用挂钩)。
我想知道这个问题是否有现有的解决方案。如果不是,最好的解决方法是什么?