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

Imports Considered Harmful

Posted on September 26, 2007
So in your layout you have something like this:
<%= stylesheet_link_tag 'main' %>

Then in your main.css you have something like:

@import "interface.css"; /* element level style */
@import "style_class.css"; /* class level style */

The problem is—how do browsers know to request a fresh copy of the imported CSS files whenever they change. When you use Rails’ helpers, an etag gets appended on the end of the requests. (that’s the ?13232352 you see on the end of rails-generated asset URLs)

Instead of using CSS @import directives, just use the rails helpers or a system like Asset Packager to group all CSS into a single file and force a download on any css change.