Should I test private methods using RSpec?

耗尽温柔 提交于 2019-12-20 09:30:02

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/16197332/should-i-test-private-methods-using-rspec

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!