本文介绍了我应该使用 RSpec 测试私有方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为私有方法编写测试是个好习惯吗?

Is it good practice to write tests for private methods?

考虑以下简单示例:

class Group
  has_many :members

  private

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

在 RSpec 中为 release_members 方法编写测试是一个好习惯吗?我相信您必须编写测试以使用 send 调用该方法,即.group.send(:release_members) 有时令人不悦.

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.

推荐答案

您可以在 Sandi Metz 演讲的这些幻灯片中找到对该主题的深入讨论.

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.

这篇关于我应该使用 RSpec 测试私有方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!