Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I test private methods using RSpec?

Is it good practice to write tests for private methods?

Consider the following simple example:

class Group
  has_many :members

  private

  def release_members
    members.each { |member| member.update_attributes group_id: nil }
  end
end

Would it be good practice to write a test for the release_members method in RSpec? I believe you'd have to write the test calling the method with send ie. group.send(:release_members) which is sometimes frowned upon.

like image 237
tyler.amos Avatar asked Apr 24 '13 16:04

tyler.amos


2 Answers

You shouldn't test private methods as they belong to the internal mechanism of the class. The purpose of Unit Tests is to check that your class behaves as expected when interacting with through its interface, i.e. its public methods.

If at a certain point you're not comfortable with long private methods, it's probably because you have here the opportunity to pull that logic outside of the class and build another module or class. Then, you can unit test it, again only its interface, i.e. its public methods.

In some rare cases, it is necessary to test the private methods because the whole internal logic is very complex and you'd like to split the problem. But in 99.9%, testing private methods is a bad idea.

like image 177
toch Avatar answered Oct 25 '22 06:10

toch


You can find an in-depth discussion of that very subject in these slides from a Sandi Metz talk.

https://speakerdeck.com/skmetz/magic-tricks-of-testing-railsconf

She says that you may test-drive your private methods if you like, but that the only test that you should worry about are the ones testing the public interface. Otherwise you may be coupling too tightly to implementation.

I think the point by toch, on splitting out service and value object and putting those under tests is also a good one if you are getting nervous about complex private methods that aren't tested.

like image 44
Joeyjoejoejr Avatar answered Oct 25 '22 06:10

Joeyjoejoejr