我有一些 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/