No Code Left Untested

Jared Carroll

Why doesn’t Rails generate a test file for each of your helpers for each of your controllers? It should, I mean its code so you have to have tests for it. All that talk you normally hear about helpers “well helpers really should have any complicated code in them…etc.”, that’s great but it never works out that way. So I decided to extend Rails’ controller generator to generate a helper test file template. The template is based off of the “testing your helpers” template found in Fowler’s Rails Recipes book. I know, the first time I saw it, I thought it was a hack but don’t worry its held up nicely so far. I’ve been using it on a couple of projects here at t-bot and our apps are that much tighter. Now there are no excuses for committing code without tests (except for views, but thats a whole other story I’m still working on). Attached is a .zip containing the extensions. I wasn’t able to get this working as a plugin so for the time being just drop it into your lib directory. Your lib should look like this:

  - controller_generator_extensions
     - controller_generator.rb
     - templates

I’ve also included a tasks directory in the .zip. In here our 2 new tasks, drop these 2 in lib/tasks. One is called test_helpers.rake, which adds a rake task to run all your helper tests like so rake test:helpers. The other is redefining the default rake task test to run your units, functionals, helpers, then integration tests – basically the same as before but also includes your helper tests.

You can run an individual helper test or an individual helper test method the same way you can w/ unit and functional tests, e.g.

ruby test/helper/users_helper_test.rb
ruby test/helper/users_helper_test.rb -n /link_to_user/

All helper tests are put in RAILS_ROOT/test/helper.

One last thing, make sure to update your config/environment.rb to load these extensions like so:

require 'lib/controller_generator_extensions/controller_generator'

These extensions have worked fine with Rails 1.2.2 and Rails 1.2.3. I have run into some strange bugs with some other versions of Rails this is due to instance variable names being changed. In lib/controller_generator_extensions/templates/helper_test.rb, the following line may need to be changed from

@controller.instance_eval { @_params = {}, @_request = request }


@controller.instance_eval { @params = {}, @request = request }

i.e. no underscores on the instance variables. As for writing your helper test methods, anything that’s available normally in a helper (#link_to, #h, etc.) is available in the helper test as well due to the various ActionView modules being included in. Enjoy.