How do you test a Rails controller method exposed as a helper_method?

Teflon Ted picture Teflon Ted · Mar 15, 2010 · Viewed 11.9k times · Source

They don't seem to be accessible from ActionView::TestCase

Answer

Jonathan Julian picture Jonathan Julian · Mar 22, 2010

That's right, helper methods are not exposed in the view tests - but they can be tested in your functional tests. And since they are defined in the controller, this is the right place to test them. Your helper method is probably defined as private, so you'll have to use Ruby metaprogramming to call the method.

app/controllers/posts_controller.rb:

class PostsController < ApplicationController

  private

  def format_something
    "abc"
  end
  helper_method :format_something
end

test/functional/posts_controller_test.rb:

require 'test_helper'

class PostsControllerTest < ActionController::TestCase
  test "the format_something helper returns 'abc'" do
    assert_equal 'abc', @controller.send(:format_something)
  end
end