Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 854
Teflon Ted Avatar asked Mar 15 '10 15:03

Teflon Ted


2 Answers

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
like image 169
Jonathan Julian Avatar answered Sep 21 '22 22:09

Jonathan Julian


This feels awkward, because you're getting around encapsulation by using send on a private method.

A better approach is to put the helper method in a module in the /controller/concerns directory, and create tests specifically just for this module.

e.g. in app controller/posts_controller.rb

class PostsController < ApplicationController
  include Formattable
end

in app/controller/concerns/formattable.rb

  module Concerns
    module Formattable
      extend ActiveSupport::Concern # adds the new hot concerns stuff, optional

      def format_something
        "abc"
      end
    end
  end

And in the test/functional/concerns/formattable_test.rb

require 'test_helper'

# setup a fake controller to test against
class FormattableTestController
  include Concerns::Formattable
end

class FormattableTest < ActiveSupport::TestCase

 test "the format_something helper returns 'abc'" do
    controller = FormattableTestController.new
    assert_equal 'abc', controller.format_something
  end

end
like image 5
Chris O'Sullivan Avatar answered Sep 21 '22 22:09

Chris O'Sullivan