Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RSpec Stub same method in loop

Tags:

ruby

stub

rspec

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?

like image 218
joshweir Avatar asked Aug 19 '26 00:08

joshweir


1 Answers

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'.

like image 65
Sergio Tulentsev Avatar answered Aug 20 '26 15:08

Sergio Tulentsev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!