[rspec-users] Mocking: brittle specs and tight coupling?

Phlip phlip2005 at gmail.com
Sun Apr 12 00:19:55 EDT 2009


Ashley Moran wrote:

> I like to view it as a sliding scale...
> 
> Pure mock specs                             Pure integration specs
>  |--------------------------------------------------------------|
> Lead more directly to good OOP          Allow rapid hack-solutions

> I think I need to sit down some time and think through more formal 
> strategies to choose when to use mocks.

There's a third alternative: Your sliding scale is really a pyramid with a peak.

The third alternative is you never _need_ to mock, yet both your tests and 
target code are highly decoupled. _That_ is the goal.

Under TDD, you get that by avoiding a design smell called "expensive setup". 
Your scale assumes that something actually must be set up - either mocks, or 
end-to-end class models. The best tests only need a few stubbed objects, each 
easy to construct.

You avoid the design smell by writing the simplest new test you can think of, 
and writing simple code to pass the test. And if you don't want that code to be 
so simplistic, you practice "triangulation".

Triangulation occurs when you have a big bowl of spaghetti, a meatball under it, 
and two chopsticks. You want to lift the meatball out, so you probe with one 
chopstick until you feel it, then you probe with the other until you can seize 
it. The two chopsticks now form a triangle, locating the meatball.

The spaghetti is the design you don't want. The meatball is the design you want. 
Each chopstick is a simple test, and the angle between the chopsticks represents 
the _difference_ between the two tests. If each test is simple yet is set up 
differently, then the simplest code which can pass both simple tests approaches 
the most elegant design.

Mock abuse just enables runaway dependencies.

-- 
   Phlip



More information about the rspec-users mailing list