Search code examples
rubyrspecprivate-methods

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.


Solution

  • 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.