[rspec-users] Write tests for objects with lots of dependencies

George Dinwiddie lists at iDIAcomputing.com
Tue Nov 15 08:08:54 EST 2011

On 11/15/11 6:30 AM, Matt Wynne wrote:
> On 15 Nov 2011, at 04:04, David Chelimsky wrote:
>> On Nov 8, 2011, at 12:52 AM, Romain Tribes wrote:
>>> Hello,
>>> I'm writing a Risk-like webgame
>>> (https://github.com/Sephi-Chan/Conquest-on-Rails) and I want to add
>>> tests, but it's painful since objects have a lot of dependencies each
>>> other.
>>> For instance, I have moved the attack logic in a dedicated class
>>> (https://github.com/Sephi-Chan/Conquest-on-Rails/blob/develop/app/models/attack.rb)
>>> and I would like to test it.
>>> The problem is that to test an attack, I need to have at least two
>>> ownerships (the relation between a territory and a participation).
>>> And to have two ownerships, I need to have many participations (the
>>> relation between a player and a game), and for that I need players.
>>> It's a lot of setup for a quite simple test.
>> If it requires a lot of set up it is inherently complex. Even though
>> the premise of the test might feel simple to you, the fact that you
>> have to negotiate your way through a web of dependencies means that
>> when something fails, you'll have a longer trail to hike to find the
>> cause. It also means your code is going to be hard to change. Loose
>> coupling is one hallmark of good, flexible software. Tests that
>> require a lot of setup expose a tightly coupled design.
> +1
> I'd recommend this book too:
> http://www.amazon.co.uk/Working-Effectively-Legacy-Robert-Martin/dp/0131177052


I'd recommend starting with 
http://objectmentor.com/resources/articles/dip.pdf as it will help you 
break those dependency chains.

>>> So, what should I do?
>> Is this a pet project for you, or something for work? If it's the
>> former, something you're using as a learning/practice vehicle, I'd
>> recommend starting over test first, and any time you find that the
>> test is starting to require complex set up, stop and rethink the design.
>>> Should I write a big setup for my suite? Or can I write a
>>> "sub-suites" with this big setup?
>> You can always extract big setup to some helper methods that set
>> things up for you. All of us do this more than we'd like to admit. But
>> it always ends up biting you in the end.

   * George Dinwiddie *                      http://blog.gdinwiddie.com
   Software Development                    http://www.idiacomputing.com
   Consultant and Coach                    http://www.agilemaryland.org

More information about the rspec-users mailing list