Pawel Janiak

South African Ruby on Rails developer, ranter, biker.

Ruby's private methods and testing

09 Jan 2014

Here’s a quick post about why you shouldn’t be testing your private methods in your Ruby unit tests.

What are private methods?

In a Ruby class, all methods that aren’t explicitly private or protected are public methods. The methods in a class are the interface that the rest of the world and other classes and objects can access objects in the class through. It is essentially an API.

If you need methods in a class that you don’t want objects other than the owner object to access, you’ll want to make them private methods. This is the same as saying you make them private in order to not expose them through the API of that object.

Benefits of private methods

The code implementation inside of private methods can be changed or refactored without any affect to the public interface. Because private methods are not tested against directly, test refactoring becomes a lot easier as does the refactoring of public methods. This is because tests are not as brittle, they test against the results, not the implementation of the private methods.

Another benefit is that using private methods allows you to write better public methods. If you keep to the rule of having a public method implementation no longer than 5 lines long and using private methods to do the actual work, your classes can start becoming much more manageable. You may for instance want to move all private methods to a module that you include in your class, making the class itself far less susceptible to churn.

It also forces you to use clear naming conventions for your private methods, making your code easier to understand as those private methods can be somewhat used as documentation.

Don’t test private methods

It is possible to test private methods by using send. Don’t do this. If you really need to test your private method, are you sure that it shouldn’t really be a public method? If not, then how much safety is your test really providing your application?