How to Test Your Helpers in Ruby on Rails

Posted on January 04, 2008

Create a new file ‘helper_test.rb’ in your test/unit directory. Example:

require File.dirname(__FILE__) + '/../test_helper'

class HelperTest < Test::Unit::TestCase
  include ActionView::Helpers::TextHelper
  include ActionView::Helpers::TagHelper
  include ApplicationHelper

  def test_base64_encoding_decoding
    foo = {:abc => 123, 'def' => :sym, 99 => 'abc'}
    base64 = encode64(foo)
    decoded = decode64(base64)
    assert_equal foo, decoded
  end

end

Include any additional helpers you want to test, just like “include ApplicationHelper” is included above.

Example app/helpers/application_helper.rb to go with the above:

require 'base64'

module ApplicationHelper

  def encode64(obj)
    Base64.encode64(obj.to_yaml).gsub(/\n/, '') # strip off newline ending
  end

  def decode64(str)
    YAML.load(Base64.decode64(str + '\n'))
  end

end