Rspec - combine expect_any_instance_of and receive counts

I need to check that any instance of my class gets a specific method, but I don't care if multiple instances get it (they should).

I tried like this:

expect_any_instance_of(MyClass).to receive(:my_method).at_least(:once) 

But, apparently, it allows only one instance to receive this method several times, but not for different instances.

Is there any way to achieve this?

+6
source share
1 answer

This is a known issue in rspec-mocks. From the v3.4 documentation for Any instance :

The rspec-mocks API is designed for individual instances of objects, but this function works with all 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 is unclear whether a particular instance will be expected to receive a name twice, or if two results are expected. (This is the first.)

Further

Using this feature is often a design odor. Perhaps your test is trying to do too much or that the test object is too complex.

Do you have any way to reorganize your test or application code to avoid a "tangled edge case"? Perhaps by building a double test and expecting it to receive messages?

+4
source

All Articles