ruby - 在 Ruby 测试中避免 protected 级别的访问器和相等方法

标签 ruby testing protected

我有一些 Ruby 代码使用 protected 级别的 attr_readers 来实现 == 方法,这样我们就可以断言一些结果日历等于预期的日历),但是除此之外的任何代码都不需要那些 protected 访问器测试代码中的断言。

我的一些代码是这样的:

class Calendar    
  def initialize(date_times)
    @date_times = date_times
  end

  def next_date_time
    @date_times.find { |time| time - DateTime.now > 0 }
  end

  def ==(other)
    @date_times == other.date_times
  end

  protected

  attr_reader :date_times
end

如何避免需要 protected attr_readers?实际上,理想情况下,如果我也可以删除对 def==(...... 的需要,那会很棒,因为它也只需要用于测试!

祝一切顺利, 亚历克斯

第一次尝试:

module Kernel
  def subclass_with_equals(class_symbol)
    clazz = Kernel.const_get(class_symbol.to_s)
    Kernel.subclass_with_default_equals(clazz)
  end

  private

  def self.subclass_with_default_equals(base_class)
    sub_class = Class.new(base_class)
    sub_class.class_eval do
      def ==(other)
        instance_variables.all? { |v| self.instance_variable_get(v) == other.instance_variable_get(v) } and other.instance_of? self.class
      end
    end
    sub_class
  end
end

在我的规范文件的顶部,我可以添加这一行来为我的类添加一个默认的 == 方法:

Calendar = sub_class_with_equals :Calendar

这使我能够从我的日历类中删除五六行!

最佳答案

您可以从测试代码中对类进行猴子修补,此时您也可以摆脱 #protected() 调用。

更好的方法可能是,从测试代码中创建一个具有访问器和 == 方法的 Calendar 子类。

关于ruby - 在 Ruby 测试中避免 protected 级别的访问器和相等方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4010661/

相关文章:

java - 使用父类(super class) "protected final"方法为子类保留公共(public)代码

json - 如何将 JSON 响应值与 Postman 环境变量匹配?

r - 何时使用训练验证测试集

java - 为什么在java中类可以有默认修饰符却不能被保护

ruby - Heroku的config/database.yml文件 "mapping values are not allowed in this context"错误如何解决

python - 是否有用于 Nose 测试的 pylint 和 pyflakes 的插件?

objective-c - 在 Objective-C 中完成 protected 属性的解决方法

ruby - Ruby 中的 SOAP JAX-WS 客户端

当超过 250 个并发连接时,Ruby SSL TCP 服务器卡住

ruby-on-rails - 如何检查是否存在值不为 "undefined local variable or method"的变量?