@kyanny's blog

My thoughts, my life. Views/opinions are my own.

Testing your helper methods in legacy Rails

In Rails 2.1 or later, you can test your helper methods by ActionView::TestCase.

Testing Helpers In Rails 2.1 | Viget

Unfortunately, legacy Rails doesn't have ActionView::TestCase. But you can write test for your helpers.

ruby - How to test custom helper in Rails? - Stack Overflow

In my case, I need to write a test for error_messages_for method that is in my ApplicationHelper and copied from Rails core. I need to a customize for error_messaages_for method. I want to get unique error message after validation. So I wrote these code. It works well for me.

https://gist.github.com/1109122

application_helper.rb

module ApplicationHelper
  def error_messages_for(*params)
    # snip
  end
end

member.rb

class Member < ActiveRecord::Base
  validates_presence_of :first_name_kana, :last_name_kana :message => "お名前(カナ)は必須入力の項目です。"
end

application_helper_test.rb

# -*- coding: utf-8 -*-
require File.dirname(__FILE__) + '/../test_helper'
require 'application_helper'

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

  context "error_messages_for" do 
    should "同じ文面のエラーメッセージは重複して表示されない" do 
      assert self.respond_to?(:error_messages_for)
      
      user = Factory(:user)
      
      @member = Member.new
      @member.valid?
      
      error_message = error_messages_for(:member)
      
      (Hpricot(error_message)/'li').map(&:inner_html).each do |key|
        assert_equal 1, error_message.scan(/#{key}/).size, "エラーメッセージ「#{key}」は一度だけ表示される"
      end
    end
  end
end