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

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

    Here is a general addition to Class which I use. It's a bit more shotgun than only making public the method you are testing, but in most cases it doesn't matter, and it's much more readable.

    class Class
      def publicize_methods
        saved_private_instance_methods = self.private_instance_methods
        self.class_eval { public *saved_private_instance_methods }
        begin
          yield
        ensure
          self.class_eval { private *saved_private_instance_methods }
        end
      end
    end
    
    MyClass.publicize_methods do
      assert_equal 10, MyClass.new.secret_private_method
    end
    

    Using send to access protected/private methods is broken in 1.9, so is not a recommended solution.

提交回复
热议问题