Having troubles with expect_any_instance_of behavior? How to expect n number of times a method is invoked?

Having troubles with expect_any_instance_of behavior? How to expect n number of times a method is invoked?

In case you are having troubles to use the

expect_any_instance_of

From Rspec, guess what, it is not only you, many of us have faced the same troubles before, you can see it here in the thread discussion
https://github.com/rspec/rspec-mocks/issues/910

I really agree with this argument:

The name of the method is “expect_any_instance_of” so I would expect this to mean that any instance could receive it. Instead, you’ve implemented it so that it refers to a single instance. So really, “expect_any_instance_of” actually means “expect_exactly_one_instance_of” and the name “expect_any_instance_of” is deceptive in my opinion and a violation of the Principle of Least Surprise.

So, to make the long story short here is what I ended up, thanks to the last comment by MaxPleaner

I have a class that makes a retry to the database let’s say

class InvoiceFinder
def self.find_with_retry
tries = 2
time_span_start = Time.zone.now
loop do
params = { user_ids: user_ids, start: time_span_start }
invoices = InvoceQuery.new(params).upcoming_invoices
if(invoices.present? || tries <= 0
break
else
time_span_start += 5.days
tries -= 1
end
end

invoices
end
end

In order to make sure the retry works we could have some Rspec just like this:

context 'when there is more than 1 retry from the database' do
before do
@counting_executions = 0
allow_any_instance_of(InvoceQuery).to receive(:upcoming_invoices) do
@counting_executions += 1
[]
end
end

it 'makes three retries to get data from the databases' do
InvoiceFinder.find_with_retry
expect(@counting_executions).to eq 3
end
end

There you, let me know any comments and thoughts, have you used any other strategy to test these sort of scenarios?
Keep learning, coding and relax.

H.

No Comments

Post A Comment