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

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

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

5条回答
  •  清歌不尽
    2021-02-18 17:59

    You could test @controller.view_context from your functional/controller tests. This method is available in Rails 3, 4, and 5, as far as I can tell.

    app/controllers/application_controller.rb

    class ApplicationController < ActionController::Base
      helper_method :current_user
      # ...
    end
    

    test/controllers/application_controller_test.rb

    require 'test_helper'
    
    class ApplicationControllerTest < ActionController::TestCase
      test 'current_user helper exists in view context' do
        assert_respond_to @controller.view_context, :current_user
      end
    end
    

    If you didn't want to test one of your controller subclasses, you could also create a test controller to verify that the method in the view_context is the same one from the controller and not from one of your view helpers.

    class ApplicationControllerHelperTest < ActionController::TestCase
      class TestController < ApplicationController
        private
        def current_user
          User.new
        end
      end
    
      tests TestController
    
      test 'current_user helper exists in view context' do
        assert_respond_to @controller.view_context, :current_user
      end
    
      test 'current_user returns value from controller' do
        assert_instance_of User, @controller.view_context.current_user
      end
    end
    

    Or, more likely, you'd want to be able to test the helper in the presence of a request.

    class ApplicationControllerHelperTest < ActionController::TestCase
      class TestController < ApplicationController
        def index
          render plain: 'Hello, World!'
        end
      end
    
      tests TestController
    
      def with_routing
        # http://api.rubyonrails.org/classes/ActionDispatch/Assertions/RoutingAssertions.html#method-i-with_routing
        # http://guides.rubyonrails.org/routing.html#connecting-urls-to-code
        super do |set|
          set.draw do
            get 'application_controller_test/test', to: 'application_controller_test/test#index'
          end
    
          yield
        end
      end
    
      test 'current_user helper exists in view context' do
        assert_respond_to @controller.view_context, :current_user
      end
    
      test 'current_user returns value from controller' do
        with_routing do
          # set up your session, perhaps
          user = User.create! username: 'testuser'
          session[:user_id] = user.id
    
          get :index
          assert_equal user.id, @controller.view_context.current_user.id
        end
      end
    end
    

提交回复
热议问题