ruby 有没有一种优雅的方法来测试一个示例方法是否是另一个示例方法的别名?

ua4mk5z4  于 12个月前  发布在  Ruby
关注(0)|答案(3)|浏览(125)

在单元测试中,我需要测试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

有什么建议?

snz8szmq

snz8szmq1#

根据Method的文档,
如果两个方法对象绑定到同一个对象并且包含相同的主体,则它们是相等的。
调用Object#method并比较它返回的Method对象将验证这些方法是否等效:

m.method(:bar) == m.method(:foo)
mmvthczy

mmvthczy2#

bk 1 e的方法在大多数情况下都有效,但我碰巧遇到了它不起作用的情况:

class Stream
  class << self
    alias_method :open, :new
  end
end

open = Stream.method(:open)
new = Stream.method(:new)
p open, new                   # => #<Method: Stream.new>, #<Method: Class#new>
p open.receiver, new.receiver # => Stream, Stream
p open == new                 # => false

输出是在Ruby 1.9中生成的,不确定这是否是一个bug,因为Ruby 1.8为最后一行生成了true。所以,如果你使用的是Ruby 1.9,那么要小心你是否混淆了一个继承的类方法(比如Class#new),这两个方法绑定到同一个对象(类对象Stream),但是Ruby 1.9认为它们是不等价的。
我的解决方法很简单-再次对原始方法使用别名,并测试两个别名的相等性:

class << Stream; alias_method :alias_test_open, :new; end
open = Stream.method(:open)
alias_test_open = Stream.method(:alias_test_open)
p open, alias_test_open                   # => #<Method: Stream.new>, #<Method: Stream.new>
p open.receiver, alias_test_open.receiver # => Stream, Stream
p open == alias_test_open                 # => true

希望这对你有帮助。

更新:

参见http://bugs.ruby-lang.org/issues/7613
因此,在这种情况下,Method#==应该返回false,因为super调用将调用不同的方法;它不是一个bug。

mccptt67

mccptt673#

调用MyClass.instance_method(:foo)将产生UnboundMethod示例,该示例具有eql?方法。
所以答案是:

describe MyClass do
  subject { described_class }

  specify do
    expect(subject.instance_method(:foo)).to be_eql(subject.instance_method(:bar))
  end
end

相关问题