Testing Rendered Output of NancyFx with the Razor View Engine Gotchas

I have been working on a small sample application called SignMeUp. My intention is to practice concepts I am learning while reading Growing Object Oriented Software Guided by Tests. I am using the awesome NancyFx micro-framework my web delivery mechanism and Razor as my view engine.

To start I have the following unit test.

[TestFixture]
public class when_visiting_the_root_of_the_site : with_a_browser
{
    private BrowserResponse response;

    public override void Given()
    {
        Configure(with =>
        {
            with.Module<RootModule>();
            with.Dependency<IEmailService>(Substitute.For<IEmailService>());
            with.Dependency<DataContext>(TestDataContextFactory.Build());
        });

        base.Given();
    }

    public override void When()
    {
        response = subject.Get("/");
    }

    [Test]
    public void it_should_be_successful()
    {
        response.StatusCode.ShouldBe(HttpStatusCode.OK);
    }

    [Test]
    public void it_should_show_the_signup_form()
    {
        response.Body["form"].ShouldExistOnce()
                .And.Attribute["action"].ShouldBe("/");
    }
}

I have been beating my head against a problem for a few days (over the course of several 1-2 hour development sessions) that has been baffling me. This test compiles and executes and the first test returns successful. The second test has always failed because the Body collection was always empty. The truly enraging thing is I could fire up the site in IISExpress and see that it worked properly.

After searching the internet high and low, trolling source repositories of example apps and finally breaking down and scouring the NancyFx source I have discovered the root of my problem.

Gotcha #1: When executing end to end tests like this from a test library you need to makes sure that your test assembly has knowledge of your views. The simplest solution for this is to set all your views to "Copy if newer" in the properties dialog in visual studio. The default view location should work from here.

Gotcha #2: Your test assembly needs to reference Nancy.ViewEngines.Razor. If you do not have this reference, Nancy will happily process your request and simply return an empty body. No error, no warning, nothing.

Follow me on Mastodon!