1. Testing Your Helpers Sucks (but necessary)

    6 January 2009

    Lately I’ve been really focusing on getting 100% code coverage and keeping my views free of all logical statements. This means moving all of the logic that would be in a view into a helper and testing that helper. In a previous post I spoke about testing your helpers. Here are some things I’ve learned since then:

    1.) Helper testing is very much like Unit Testing (hell, it *is* unit testing). When I first was getting into helper testing I thought that the Rails test directory should have an extra folder called “helpers”. I now think that the “helpers” should be under the “unit” folder. In fact, there should probably be a “models” folder in there too to keep everything separate.

    2.) Testing your helpers can be a real pain in the ass when your helper calls any regular ActionController#base methods. For example, a few of my helpers might make a call to render a partial. Good luck on getting this to work in your helper tests. Because the helper is just a module that is being included into the unit test you don’t have access to everything that you normally would. Instead I had to mock out the render method. Saying this of course really makes me look like a dickhead.

    3.) The expected results from your helpers is most likely HTML. Testing against this SUCKS! The HTML can be very verbose sometimes, and I feel like I am just wasting a lot of time hard coding expected HTML from my helper. And most of the time the tests fail because the spacing or order of the tag elements are off. I have recently been cheating and just pattern matching against expected HTML params. I think this is okay to do because I use Rails’ content_tag method to generate the elements so there should be no chance of illegal HTML being generated.

    In the end, is it worth it to test helpers? I’m not entirely sold to tell you the truth. I believe that you should be TATFT but there comes a point when the cost outweighs the benefit. I feel that helper testing is just view testing in disguise. The only thing keeping me testing my helpers is that there is logic in them.