是否可以在测试中访问对象收到某条消息的次数?我的目标是测试一个类已经收到两次类方法调用相同的次数。
从逻辑上讲,似乎这个计数会在代码执行时存储在某个地方。
这看起来像
allow(SomeClass).to receive(:method_1).at_least(1).times
allow(SomeClass).to receive(:method_2).at_least(1).times
# setup and code here
expect(method_1_received_times).to eq (method_2_received_times)
答案 0 :(得分:3)
不是很漂亮,但你可以设置自己的计数器:
@method_1_received_count = 0
@method_2_received_count = 0
allow(SomeClass).to receive(:method_1) { @method_1_received_count += 1 }
allow(SomeClass).to receive(:method_2) { @method_2_received_count += 1 }
# setup and code here
expect(@method_1_received_count).to eq(@method_2_received_count)