Testing Helpers In Rails 2.1

The conventional approach to testing helpers in Rails has, until recently, always been relatively subjective. I have come across different strategies including generators, plugins and hand-hacked setups depending on where I looked. In sharp contrast, the controller testing convention has been DRY'd up and moved into the framework in the form of the ActionController::TestCase class. Fortunately, Brian has been working on some helper testing tools and recently stumbled across the ActionView::TestCase class. If you have been looking for a convenient, framework supported way to test your helpers, look no further. This class provides the same conventions as ActionController::TestCase and makes testing helpers a breeze.

Test Your Helpers Using ActionView::TestCase
Here is an example that shows how to use ActionView::TestCase along with Brian's assert_tag_in. First, create a test named HelperNameTest and inherit from ActionView::TestCase. Then just call your helper methods from your tests, it's that easy.

 module ApplicationHelper def special_header() content_tag :div do link_to('Edit Profile', edit_account_path) end end end class ApplicationHelperTest < ActionView::TestCase def test_special_header_should_render_edit_link tag = special_header(:edit_profile => true) assert_tag_in(tag, :a, :attributes => {:href => edit_account_path}) end end 

Worth noting here is the ability to test methods that rely on url_for without needing to create a temporary controller in your own testing code. I also want to point out that Chu Yeow did cover using ActionView::TestCase in his Living on the Edge series, but it totally slipped past me :)


ActionView::TestCase is not loaded automatically. Be sure to require 'action_view/test_case' in your test_helper.

Justin Marney

Posted in Article Category: #Code