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?
-
publicis a method that takes1..nsymbols representing the names of instance methods, and makes them public. -
self.private_instance_methodsreturns all the private instance methods ofFoo(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 forpublicthus essentially making all private methods ofFoopublic. The same works with protected methods if you useprotected_instance_methodsinstead :)
Written by Lucas
Related protips
1 Response
Great, didn't know that until now. Thanks for sharing.
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Ruby
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#