joshweir joshweir - 1 year ago 64
Ruby Question

RSpec Stub same method in loop

Using RSpec, I want to:

expect(Thing).to receive(:status)
.with(for: 'something')
.and_return('down')


on the first iteration, and the same stub should return a different return on the 2nd iteration:

expect(Thing).to receive(:status)
.with(for: 'something')
.and_return('up')


when testing the below code snippet:

2.times do |i|
break if Thing.status(for: 'something') == 'up'
sleep 2
raise MyError if i > 0
end


How would I do this?

Answer Source

Just stub once and supply all the return values.

expect(Thing).to receive(:status)
                .with(for: 'something')
                .and_return('down', 'up')

First time status is called, it will return 'down'. Second time it will return 'up'.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download