1. Testing Your Helpers with Autotest

    26 November 2008

    So I’ve been writing an app lately and I am really trying to go for 100% test code coverage. When I ran into the issue of TDDing my helpers I recalled a post by Josh Nichols: Helper Testing Using ActionView::TestCase. This was a really good start but it felt somewhat incomplete. I didn’t like the idea of putting my helper tests into test/unit/helpers. So let me go through my process:

    I wanted to create some helpers to generate a user menu, “Sign Up / Login” if you are not currently logged in, “Profile / Logout” if you are.

    So here are the tests I wrote:



    Some things I should point out is that the relative path to test_helper is one less directory because this test lives in: test/helpers not test/unit/helpers (this is different than Josh’s example)

    Also, like Josh I am using Shoulda. But I am wrapping the entire test in an empty context with a general setup that does two things.
    1.) stubs out protect_against_forgery? in the controller so that I can generate POSTs
    2.) creates a @request object so I can interact with the session.

    I could also put in code to create cookies but I am doing TDD and should only create the code necessary. (but it is a good thing to keep in mind) Also, as soon as I have two helpers I will probably refactor this setup out into test_helper so I can DRY the code up a bit.

    Now I run autotest and… nothing. My test isn’t included. So let’s look at why this is.

    autotest is part of the ZenTest gem. There is a library that is Rails specific ZenTest/lib/autotest/rails.rb

    Check out the initialize method:



    We are interested in the 3rd add_mapping method

    That is how autotest is running our Rails tests. So, you could edit the gem but we don’t want to do that. Autotest allows you to extend it by creating a .autotest file in the root of your project. After checking out the ZenTest RDoc you can see that we can hook into Autotest and tell it to do what we want. Okay, so here is my simple hook for adding the test/helpers directory to .autotest:



    I intentionally kept it as a regular expression so I can easily add more directories if I need them in the future.

    Run autotest and hurray! Now my helpers are apart of the test suite. Of course now I have to make them pass. :)

    Red - Green - Refactor
    TATFT