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

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

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

5条回答
  •  青春惊慌失措
    2021-02-18 17:49

    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
    

提交回复
热议问题