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

后端 未结 5 2479
眼角桃花
眼角桃花 2021-02-18 17:22

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

5条回答
  •  不思量自难忘°
    2021-02-18 18:03

    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
    

提交回复
热议问题