[rspec-users] how to spec a recursive method that creates db records?

Stephen Eley sfeley at gmail.com
Tue Jul 21 02:31:58 EDT 2009

On Tue, Jul 21, 2009 at 2:05 AM, Barun Singh<barunio at gmail.com> wrote:
> This isn't a question of refactoring; I can
> easily refactor the method as you describe but this doesn't resolve the
> issue (indeed, it just leads to an increased number of public methods in the
> model with no real benefit).

Why would they have to be public?

> I can easily spec the find_something and add_something methods so I know
> that they work correctly.  My question is, how do I write a spec for
> find_or_add_something in a way where I don't have to re-test the behavior of
> the individual find_something and add_something methods a second time, and
> can just test the overall logic of that method?

My answer for that remains the same: spec it from the outside.  Treat
it as a black box.  Set up an initial state, then write specs that
express the expectation that inputs A, B, and C should yield output D.
 (Where D might be a database record, or a returned value, or both, or
whatever.)  The number of specs you write in this manner will depend
on the number of interesting ways that your method could go right or
wrong.  You may need to provide multiple initial states as well, but
that's easy in RSpec with nested 'describe' or 'context' blocks.

That the method calls 'add_something' and 'find_something' on the
inside is immaterial.  You don't have to isolate everything from
everything else.  If we stubbed every method call inside every method
we tested, we'd soon get to the point where we were stubbing '+' or
'gsub' or 'print.'

Your specs shouldn't have to care how 'find_and_add_something' works.
What you are expressing is that it DOES work.  Test the inputs and
outputs, and let it call whatever it wants to get from one to the

Have Fun,
   Steve Eley (sfeley at gmail.com)
   ESCAPE POD - The Science Fiction Podcast Magazine

More information about the rspec-users mailing list