Should I test private methods using RSpec?

2020-05-19 04:51发布

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.

2条回答
Luminary・发光体
2楼-- · 2020-05-19 05:46

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.

查看更多
Deceive 欺骗
3楼-- · 2020-05-19 05:46

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.

查看更多
登录 后发表回答