【发布时间】:2014-10-27 09:16:18
【问题描述】:
我想优化一些速度较慢的规格。 此类规范的示例如下所示:
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
但不幸的是,我什至看不到从哪里开始实施它。它存在多个潜在问题(是否应该在共享结果上调用挂钩)。
我想知道这个问题是否有现成的解决方案。 如果没有,最好的解决方法是什么?
【问题讨论】:
-
除非您希望您的字符串在测试之间发生变化,否则为什么不在
before(:all)块中设置一次?
标签: ruby-on-rails ruby rspec rspec2 rspec3