【发布时间】:2021-05-15 10:54:33
【问题描述】:
我正在尝试测试一个 ruby 方法在每个块中从它内部调用另一个方法
示例类
class A
def foo
return 'foo'
end
end
class B
def initialize
@array_of_class_a_instances = []
end
def bar
@array_of_class_a_instances.each do |element|
element.foo
end
end
end
我想为 B 类中的 bar 方法编写一个单元测试,以验证 foo 方法被调用的次数是 @array_of_class_a_instances 长。如果我们说数组有 4 个元素,我想测试 foo 方法被调用了 4 次。我有一个可以在下面工作的测试,但它使用了多个期望语句。是否有一些语法可以只用一个来编写?
describe B do
describe '#bar' do
# ommitted for brevity
small_b = B.new
it 'calls the foo method for each element in the array' do
expect(small_b.array_of_class_a_instances[0]).to receive(:foo).exactly(1).time
expect(small_b.array_of_class_a_instances[1]).to receive(:foo).exactly(1).time
expect(small_b.array_of_class_a_instances[2]).to receive(:foo).exactly(1).time
expect(small_b.array_of_class_a_instances[3]).to receive(:foo).exactly(1).time
small_b.bar
end
end
end
【问题讨论】: