This post is over 6 months old. Some details, especially technical, may have changed.

Debugging NSpec Tests: The DebuggerShim

Busy busy busy. I've been working away on a lot of projects and not had a lot of time to stick anything up on this blog in a while. I've got a growing "To Blog" list but no time to do it, woe is me!!!

Enough about my perfectly normal life, well almost. Some of my current work has me going full tilt with TDD on a little C# project and I decided that NSpec would help me with unit testing. So I went about writing failing tests, writing code, passing tests on and on and on. Things went along fairly well until I hit a little bit of a wall around a little edge case. My tests kept failing and I couldn't understand why. The stack trace made little to no sense and my code looked sound. The problem I had was that NSpec, out of the box at least, doesn't have any nice integration with Visual Studio or TestDriven.NET. Initially I was using a throw away console application and debugging through it but as you can imagine that was time consuming.

It wasn't long though until I was pointed in the right direction.

If you want to have debugger support for you NSpec specifications, use this: http://t.co/6SwZcVL /cc @kouphax @mattfloless than a minute ago via web Favorite Retweet Reply

The gist, in full below, provides a simple debugger shim over nspec that allows you to hook into the Visual Studio debugger (through something like TestDriven.NET for example). I simply right clicked on the shim and select "Run With Debugger" and boom my stupid mistake was displayed to me rather quickly.

using System;
using NUnit.Framework;
using NSpec.Domain;
using System.Reflection;
using NSpec;

namespace DynamicBlog.Tests
{
    [TestFixture]
    public class DebuggerShim
    {
        [Test]
        public void debug()
        {
            //the specification class you want to test
            //this can be a regular expression
            var testClassYouWantToDebug = "describe_Blog";

            //initialize NSpec's specfinder
            var finder = new SpecFinder(
                Assembly.GetExecutingAssembly().Location,
                new Reflector(),
                testClassYouWantToDebug);

            //initialize NSpec's builder
            var builder = new ContextBuilder(
                finder,
                new DefaultConventions());

            //this line runs the tests you specified in the filter
            new ContextRunner(builder, new ConsoleFormatter()).Run();
        }
    }
}

Handy until a more concrete solution appears. One more thing - really enjoying nspec, it seems to be fitting well with the way I work.

Published in Testing .NET on July 04, 2011