Update: this blog is no longer active. For new posts and RSS subscriptions, please go to http://saintgimp.org.
I’ve previously written about the Behavior-Driven Development style of TDD and about how to use such a style in MSTest. I’ve done this on several personal and business projects and it’s worked pretty well, but I recently got around to trying Aaron Jensen’s MSpec and I have to say there’s no going back. Conceptually my tests are the same but mechanically MSpec just flows so much better.
Here’s test context from a personal game project of mine written in my old MSTest BDD framework:
public class when_the_planet_is_initialized : PlanetContext
protected override void Context()
protected override void BecauseOf()
public void should_initialize_the_renderer()
_planetRenderer.AssertWasCalled(x => x.Initialize(_radius));
public void should_create_terrain()
_terrainFactory.AssertWasCalled(x => x.Create(_radius));
It works, but it’s noisy.
Now here’s the same context re-written in MSpec:
Because of = () =>
It should_initialize_the_renderer = () =>
It should_create_terrain = () =>
The MSTest version requires 25 text lines, the MSpec version 12 text lines. This context doesn’t require an “Establish context” delegate, but if I wanted to add one later the form is the same as the other clauses and I don’t have to remember to call a base class version. There’s far less compiler gook getting in the way and the code reads very easily. It just oozes elegance. Ok, I suppose Rubyists or Pythonistas might still call this noisy but for C# it’s amazing. It can be daunting at first when your brain exclaims, “That can’t possibly be legal C# code!” but once you figure out that it’s just lambda expressions assigned to delegate fields it all makes perfect sense.
MSpec also includes BDD specification extension methods very similar to the ones I wrote about so you don’t have to worry about writing and maintaining that code, either.
If you’re at all interested in BDD, you owe it to yourself to try MSpec!