Hi --

On Sat, 2 Aug 2008, Phlip wrote:

> Shadowfirebird wrote:
>
>> I've found this lovely bit of example code for mocha, though -- see
>> below.  If I understand you correctly, you seem to be saying that you
>> *don't* test the output routine; you use a mock to fake it so that you
>> can test the rest of the code?
>
> Consider a test T that calls A, which calls B.
>
> Sometimes, a B is cheap to assemble, so T can assemble B, activate A, and 
> test that A did its thing. T considers B's behavior just a side-effect.
>
> Most of the time, B should be real. And its state should be static (such as a 
> Rails "fixture", with static data.) B should not have runaway dependencies. 
> The test T should be easy to set-up.
>
> You should mock B if it's too expensive to set up.

Mocking is also good for pinpointing exactly what you want to test and
what you don't, even if not mocking wouldn't be that expensive in
resources. For example, there's the classic Rails create method, which
goes like this:

   if new record is saved successfully
     go do something
   else
     do something else
   end

In this case, you can certainly do a real saving of the object. But if
you want to test *only* the conditional logic, and make sure that the
controller takes the right branch given a record whose answer to "Did
you save?" is always "Yes" or always "No", then you can use a mock
object.

> For example, if B reads the system clock, and if T would prefer the
> date is 2008 July 31, the test T should not wait an infinite amount
> of time, until the cosmos oscillates and 2008 July 31 occurs again.
> Tests should run as fast as possible, to avoid any hesitation
> running them.
>
> You should mock B, so it behaves as if the date is correct. Or you should 
> mock (in Ruby) Time.now, so all Ruby methods that use the date will read the 
> mocked date.
>
> Other examples of things too expensive to directly test:
>
> - live users
> - random numbers
> - hardware - networks, robots, tape drives, the clock, etc
> - system errors
>
> If your B object is not on the list, you should not mock it.

I wouldn't narrow it down that strictly. It can depend on the purpose
of the test, as well as the profile of the thing you're mocking.


David

-- 
Rails training from David A. Black and Ruby Power and Light:
  *  Advancing With Rails    August 18-21    Edison, NJ
  * Co-taught by D.A. Black and Erik Kastner
See http://www.rubypal.com for details and updates!