What's the best way to unit test protected & private methods in Ruby?

后端 未结 16 610
被撕碎了的回忆
被撕碎了的回忆 2020-12-12 10:47

What\'s the best way to unit test protected and private methods in Ruby, using the standard Ruby Test::Unit framework?

I\'m sure somebody will pipe up a

16条回答
  •  暖寄归人
    2020-12-12 11:30

    In order to do this:

    disrespect_privacy @object do |p|
      assert p.private_method
    end
    

    You can implement this in your test_helper file:

    class ActiveSupport::TestCase
      def disrespect_privacy(object_or_class, &block)   # access private methods in a block
        raise ArgumentError, 'Block must be specified' unless block_given?
        yield Disrespect.new(object_or_class)
      end
    
      class Disrespect
        def initialize(object_or_class)
          @object = object_or_class
        end
        def method_missing(method, *args)
          @object.send(method, *args)
        end
      end
    end
    

提交回复
热议问题