[rspec-users] Mocks and Refactoring - doing it wrong?

Scott Taylor mailing_lists at railsnewbie.com
Thu Oct 30 01:26:01 EDT 2008

On Oct 30, 2008, at 1:02 AM, Sebastian W. wrote:

> Hello RSpec folks,
> I've only been introduced to the world of mock objects since Wednesday
> of last week, so go easy on me if I come off as ignorant. :P
> So, I'm a big fan of testing, especially since it has really helped to
> do refactoring in the past. But, I'm running into an issue that I'm
> hoping could be cleared up. Let's say that I have some code like the
> following:
> mock_engine = mock("Engine")
> mock_engine.should_receive(:ignite)
> car = Car.new(mock_engine)
> car.start
> Internally, the car class calls "ignite" on the engine that was passed
> to the constructor. We run the spec, everything is green. So far, so
> good.
> Now, here's what I don't understand: suppose I refactor the Engine  
> class
> and rename the "ignite" method to "turn_on". If I re-run the example
> from above, the test is still green - but it shouldn't be, since the
> "ignite" method doesn't exist on the Engine class anymore.
> So I'm wondering...what am I doing wrong? I feel like my tests should
> help catch these sorts of things when I do a refactoring - my hunch is
> that I'm missing a step here.

The step your missing is that using mocks is different then classical,  
black box testing.

When you use a mock object, you're making a tradeoff.   One of the  
things you gain is isolation.  For instance, if you were testing a  
webservice or a database, you may not care about it being around *for  
this test*.  Another thing you're gaining is pure speed (of the  
running test case) - you simply won't have to go through the full  
stack.  On the other hand, that's also what your loosing - meaning  
that if that API changes, your screwed.

This is why anyone who knows anything about testing will recommend  
several different layers of tests - some very close to the metal which  
will use mocks (which can be repeatedly run quickly), and others which  
are closer on the integration side of the spectrum.


More information about the rspec-users mailing list