[rspec-users] specs on private methods

Pat Maddox pergesu at gmail.com
Thu Jan 10 01:56:19 EST 2008


On Jan 9, 2008 5:26 AM, Richard Conroy <richard.conroy at gmail.com> wrote:
> On Jan 8, 2008 7:14 PM, Daniel Tenner <daniel.ruby at tenner.org> wrote:
> > Might be a personal thing, but my approach is that I try to test the
> > public behaviour of the object. Testing private methods is, imho,
> > getting dangerously close to specifying how the object does its
> > business, rather than what it does.
> >
> > I would just spec the externally visible behaviour, where it occurs,
> > and let the object implement it as it wants (using private methods or
> > any other mechanism).
>
> The trouble is that this makes it very difficult to get effective coverage.
> There is usually a lot more setup involved. If your tests are more expensive
> to write, because you are unit testing indirectly through public methods,
> less testing will get done, and worse tests can end up getting very brittle.

I've found that this is symptomatic of a bad design.  Specifically, it
smells of an SRP violation or tight coupling.

One thing I think people don't realize is that a bit of code should be
easiest to use in a test.  We test objects in isolation, they don't
depend on expensive external resources, etc.  If you can't use the
code within a test harness - that is, write a test for it - then how
can you possibly expect to use it in production?

In practice, of course, this can all be very difficult.  I recommend
reading "Working Effectively with Legacy Code" by Michael Feathers for
some excellent strategies on how to make existing gnarly code easier
to test.


> I do like the idea though of during the unit test itself, you unseal the method.
> You get the best of both worlds.

Not really.  You get test coverage, which is good, but at the expense
of carefully thinking why your design might be wrong.

Pat


More information about the rspec-users mailing list