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

David Chelimsky dchelimsky at gmail.com
Mon Nov 14 23:04:44 EST 2011


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.

> 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. 

HTH,
David



More information about the rspec-users mailing list