Rspec: How to check recursion?

I would like to verify that a method is called recursively with a specific argument.

My approach:

class Recursable def rec(arg) rec(7) unless arg == 7 end end describe Recursable do it "should recurse" do r = Recursable.new('test') r.should_receive(:rec).with(0).ordered r.should_receive(:rec).with(7).ordered r.rec(0) end end 

Suddenly RSpec does not work:

 expected :rec with (7) once, but received it 0 times 

Any idea what is wrong with my approach? How to check efficient recursion with a specific argument?

+7
ruby recursion mocking rspec
source share
2 answers

The problem with your test, as of right now, is that you are deleting the method that you are trying to test. r.should_receive(:rec) replaces r#rec stub, which of course never calls r.rec(7) .

A better approach would be to simply check if the result of the initial method call is correct. It is not necessarily important whether the method is repeated, iterated, or the friend’s phone if it gives the correct answer at the end.

+10
source share

Often, if you need to test recursion, this is the smell of code; you should probably divide the method into different responsibilities or something like that.

But sometimes you just need to add some basic checks for your recursion. You can do this with rspec and_call_original :

 it "should recurse" do r = Recursable.new('test') r.should_receive(:rec).with(0).ordered.and_call_original r.should_receive(:rec).with(7).ordered.and_call_original r.rec(0) end 

Normally, should_receive simply drown out the real method, so recursion does not work. Using and_call_original method (which contains validation checks) will also call the implementation of the original method, which will perform the recursion as expected.

+2
source share

All Articles