RSpec tips & tricks #1

Thales Oliveira
coding breeze
Published in
1 min readDec 29, 2015

Every now and then you face code like this to test?

# this code is inside some nice file that is not "user.rb"if !user.done_stuff?
user.do_suff
if user.done_stuff?
...
end
end

“done_stuff?” is an external method on the User class and you don’t want to test that. But we do need to test the code after the second if. So what do you do? You might happily say: “Let’s set up and expectation!”

expect(user).to receive(:done_stuff?).and_return(false)

Nice. But the test is still failing, OH NOEZ ): Why is that? Because “done_stuff?” must return “false” only on the first call, not in the second. Uhmmm, tricky!

Well, the RSpec fellas got us covered! By doing fancy black magic you might ask? Nope, the solution couldn’t be simpler: “and_return” accepts multiple values separated by a comma! And they will be returned in the order you specify when the method is called. So:

expect(user).to receive(:done_stuff?).and_return(false, true)

The test is now green! Yaaay!

Hope you enjoyed this tip. Have fun!

--

--