Helper Testing Independence

Brian Landau, Former Developer

Article Category: #Code

Posted on

Testing helpers is a topic we’ve covered a couple times already here on the Viget Extend blog. I’ve additionally submitted a patch to Rails for adding some helper assertions to ActionView and other helper related testing goodness. But until that gets accepted and committed, I thought I’d hold everyone over with a helper testing plugin.

Independently Testing Helpers

The main tenet here is that helper functionality should be tested outside of another context (i.e. the controller). To achieve that, we need to create helper tests that live independent of our other tests. As Justin pointed out, Rails actually provides a class to assist in this, ActionView::TestCase.

The plugin I’ve created has two generators that help in creating these tests. The first, helper_tests, can be used to generate tests for your existing helpers. It creates a test file for each helper in the test/helpers directory and a test method for each public helper method. You can also pass it a list of helpers you wish to generate tests for and it will skip those that you don’t name.

Usage:

> script/generate helper_tests [SampleHelper Admin::AnotherHelper ...]

The other generator, helper, creates a helper -- and a helper test for the name provided. It will also accept a list of methods for the helper and generate them, as well as tests for each one.

Usage:

> script/generate helper HelperName [methods ...]

All generated helper tests will be run with rake test now along with all the other tests. Also a rake test:helpers task is provided to run just the helper tests.

Bonus Assertions!

That’s right ... I’ve also rolled in assert_tag_in, assert_tag_not_in, assert_select_in, assert_hpricot_in, and assert_hpricot_not_in assertions to the ActionView::TestCase class. These work exactly like their ActionController counterparts, except for the Hpricot ones, of course. These work by simply passing them the HTML string, and either a CSS selector or a XPath selector. The method then looks for an element matching the selector.

In the future, I’d like to spiffy assert_hpricot_in up by making it more like assert_select but it’s still useful to all Hpricot lovers out there as-is.

The Helper Me Test plugin:

The plugin is up on GitHub: http://github.com/vigetlabs/helper_me_test/tree/master

The clone URL to install with: git://github.com/vigetlabs/helper_me_test.git

As always comments, suggestions, or whatever are welcome, as well as forking it and adding your own twist.

Related Articles