我应该使用RSpec测试私有方法吗? [英] Should I test private methods using RSpec?

查看:115
本文介绍了我应该使用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 ie调用该方法的测试. 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测试私有方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆