Last Updated: February 25, 2016
·
2.131K
· x3ro

Easily test private and protected methods in Ruby

When writing unit tests, one should generally test the public API of a class. Sometimes, however, it might be necessary/desireable to also test private methods (there is plenty of discussion on that topic out there, and I really don't want to get into that ;-). But, what's the best way to unit test protected & private methods in Ruby?.

The linked to SO question contains quite a few suggestions. I really can't say which of them might be the best one, but here's an easy one that isn't listed. Let's assume that you've got the following class:

class Foo
    private
    def bar
        42
    end
end

And you'd like to test the private method bar, then you can simply add the following, for example to your test helper class:

class Foo
    public *self.private_instance_methods(false)
end

What does it do?

  • public is a method that takes 1..n symbols representing the names of instance methods, and makes them public.
  • self.private_instance_methods returns all the private instance methods of Foo (duh) as a list, and the boolean parameter indicates whether or not to include inherited methods (which we don't want in this case).
  • The splat operator (the *) unpacks the returned list as parameters for public thus essentially making all private methods of Foo public. The same works with protected methods if you use protected_instance_methods instead :)

1 Response
Add your response

Great, didn't know that until now. Thanks for sharing.

over 1 year ago ·