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

后端 未结 16 603
被撕碎了的回忆
被撕碎了的回忆 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:19

    Just reopen the class in your test file, and redefine the method or methods as public. You don't have to redefine the guts of the method itself, just pass the symbol into the public call.

    If you original class is defined like this:

    class MyClass
    
      private
    
      def foo
        true
      end
    end
    

    In you test file, just do something like this:

    class MyClass
      public :foo
    
    end
    

    You can pass multiple symbols to public if you want to expose more private methods.

    public :foo, :bar
    

提交回复
热议问题