Rspec - combine expect_any_instance_of and a receive counts

Mat picture Mat · Feb 10, 2016 · Viewed 9k times · Source

I need to verify that any instance of my class receives a certain method, but I don't care if many instances receive it (they're supposed to).

I tried like this:

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

But apparently, it only allows for a single instance to receive the method multiple times, but not for different instances.

Is there a way to achieve that?

Answer

Gabriel Deal picture Gabriel Deal · May 7, 2018

If you need to live with the code smell, this rspec-mocks Github issue suggests a solution along these lines:

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