views:

40

answers:

1

I'd like to test 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

Unexpectedly, RSpec fails with:

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

Any idea what's wrong with my approach? How to test for effective recursion with a specific argument?

+5  A: 

The problem with your test as it is now is that you are stubbing away the method you are trying to test. r.should_receive(:rec) is replacing r#rec with a stub, which of course doesn't ever call r.rec(7).

A better approach would be to simply test that the result of the initial method call is correct. It shouldn't strictly matter whether or not the method recurses, iterates, or phones a friend, as long as it gives the right answer in the end.

Nick Lewis
Ah, okay. Oh, well! I am trying to find a bug - the method does return a wrong value (it is more complicated than depicted here). I thought I could test each part of it in order to narrow down the problem space. It gets more complicated with each level of recursion and it would have been nice to test whether the recursion is executed correctly.
duddle