Rspec - 组合 expect_any_instance_of 和接收计数
Rspec - combine expect_any_instance_of and a receive counts
我需要验证我的 class 的任何实例都接收到某个方法,但我不关心是否有很多实例接收到它(它们应该接收到)。
我这样试过:
expect_any_instance_of(MyClass).to receive(:my_method).at_least(:once)
但显然,它只允许单个实例多次接收该方法,而不能用于不同的实例。
有办法实现吗?
这是 rspec-mocks 中的一个已知问题。来自 Any instance
上的 v3.4 documentation:
The rspec-mocks API is designed for individual object instances, but this feature operates on entire classes of objects. As a result there are some semantically confusing edge cases. For example, in expect_any_instance_of(Widget).to receive(:name).twice
it isn't clear whether a specific instance is expected to receive name twice, or if two receives total are expected. (It's the former.)
此外
Using this feature is often a design smell. It may be that your test is trying to do too much or that the object under test is too complex.
您有什么方法可以重构您的测试或应用程序代码来避免 "confusing edge case"?也许通过构造一个测试替身并期望它接收消息?
如果您需要忍受代码的味道,this rspec-mocks Github issue 建议采用以下方式的解决方案:
receive_count = 0
allow_any_instance_of(MyClass).to receive(:my_method) { receive_count += 1 }
# Code to test here.
expect(receive_count).to be > 0
我需要验证我的 class 的任何实例都接收到某个方法,但我不关心是否有很多实例接收到它(它们应该接收到)。
我这样试过:
expect_any_instance_of(MyClass).to receive(:my_method).at_least(:once)
但显然,它只允许单个实例多次接收该方法,而不能用于不同的实例。
有办法实现吗?
这是 rspec-mocks 中的一个已知问题。来自 Any instance
上的 v3.4 documentation:
The rspec-mocks API is designed for individual object instances, but this feature operates on entire classes of objects. As a result there are some semantically confusing edge cases. For example, in
expect_any_instance_of(Widget).to receive(:name).twice
it isn't clear whether a specific instance is expected to receive name twice, or if two receives total are expected. (It's the former.)
此外
Using this feature is often a design smell. It may be that your test is trying to do too much or that the object under test is too complex.
您有什么方法可以重构您的测试或应用程序代码来避免 "confusing edge case"?也许通过构造一个测试替身并期望它接收消息?
如果您需要忍受代码的味道,this rspec-mocks Github issue 建议采用以下方式的解决方案:
receive_count = 0
allow_any_instance_of(MyClass).to receive(:my_method) { receive_count += 1 }
# Code to test here.
expect(receive_count).to be > 0