在单元测试中,我需要测试alias_method定义的别名方法是否已经正确定义。我可以简单地对用于其原始别名的别名使用相同的测试,但我想知道是否有更明确或更有效的解决方案。例如,有没有一种方法可以1)取消引用一个方法别名并返回它的原始名称,2)获取并比较某种底层方法标识符或地址,或者3)获取并比较方法定义?举例来说:
class MyClass
def foo
# do something
end
alias_method :bar, :foo
end
describe MyClass do
it "method bar should be an alias for method foo" do
m = MyClass.new
# ??? identity(m.bar).should == identity(m.foo) ???
end
end
有什么建议?
3条答案
按热度按时间snz8szmq1#
根据Method的文档,
如果两个方法对象绑定到同一个对象并且包含相同的主体,则它们是相等的。
调用
Object#method
并比较它返回的Method
对象将验证这些方法是否等效:mmvthczy2#
bk 1 e的方法在大多数情况下都有效,但我碰巧遇到了它不起作用的情况:
输出是在Ruby 1.9中生成的,不确定这是否是一个bug,因为Ruby 1.8为最后一行生成了
true
。所以,如果你使用的是Ruby 1.9,那么要小心你是否混淆了一个继承的类方法(比如Class#new),这两个方法绑定到同一个对象(类对象Stream
),但是Ruby 1.9认为它们是不等价的。我的解决方法很简单-再次对原始方法使用别名,并测试两个别名的相等性:
希望这对你有帮助。
更新:
参见http://bugs.ruby-lang.org/issues/7613
因此,在这种情况下,
Method#==
应该返回false,因为super
调用将调用不同的方法;它不是一个bug。mccptt673#
调用
MyClass.instance_method(:foo)
将产生UnboundMethod示例,该示例具有eql?
方法。所以答案是: