[rspec-users] more rspec questions

Adam Sroka adam.sroka at gmail.com
Tue Apr 27 17:39:15 EDT 2010


On Tue, Apr 27, 2010 at 2:20 PM, Patrick J. Collins
<patrick at collinatorstudios.com> wrote:
> Hi everyone,
>
> I still am on my quest to understand Rspec, and I have a few new questions...
>
> If I have a "complex" method which calls other methods, say something like:
>
> -----
>
> class Foo
>
>  def complex_method
>         setup
>    setup_something_else
>
>         mini_method1
>         mini_method2
>         mini_method3
>  end
>
>  private
>
>  def setup
>    @somevar = Something.something_else
>  end
>
>  def setup_something_else
>    @someothervar = SomethingElse.something_else
>  end
>
>  def mini_method1
>    # do something
>  end
>
>  ... etc
> end
>
> -----
>
> One way to properly test this would be to write a spec that calls
> complex_method and it's output returns what I am expecting..  but if it's
> broken, it becomes difficult for me to figure out why without writing
> individual tests for the mini_methods.
>

Yep. You need small focused specs that each test one bit of behavior
so that when they fail you know why.

> However, I cannot do tests for mini_methods because they are private, and 2ndly
> they require initializer methods (setup/setup_something_else) to be called.
>

What if they didn't? Is there a different way you could design this so
that the interesting bits (The small methods) didn't depend so much on
the other bits around them?

BTW, those kind of dependencies are what design experts call coupling.
Over the years many of us have come to believe that less coupling ==
better design. The fact that your spec is telling you that this is
hard to test is a really important clue that the design could be
improved.

> So I am just wondering, what is the proper technique to test these
> private mini_methods?
>

Make them public. Move them to their own classes that encapsulate the
stuff they need to know about (e.g. the "setup".) When you test the
higher level methods you can mock this stuff. When you test the small
methods you should call them directly.

There are a number of other techniques that might be helpful too. If
you have a more specific example of what you are trying to do we might
be able to give you more specific advice.


More information about the rspec-users mailing list