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

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

    Similar to @WillSargent's response, here's what I've used in a describe block for the special case of testing some protected validators without needing to go through the heavyweight process of creating/updating them with FactoryGirl (and you could use private_instance_methods similarly):

      describe "protected custom `validates` methods" do
        # Test these methods directly to avoid needing FactoryGirl.create
        # to trigger before_create, etc.
        before(:all) do
          @protected_methods = MyClass.protected_instance_methods
          MyClass.send(:public, *@protected_methods)
        end
        after(:all) do
          MyClass.send(:protected, *@protected_methods)
          @protected_methods = nil
        end
    
        # ...do some tests...
      end
    

提交回复
热议问题