views:

57

answers:

1

In a unit test I need to test whether alias methods defined by alias_method have been properly defined. I could simply use the same tests on the aliases used for their originals, but I'm wondering whether there's a more definitive or efficient solution. For instance, is there a way to 1) dereference a method alias and return its original's name, 2) get and compare some kind of underlying method identifier or address, or 3) get and compare method definitions? For example:

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

Suggestions?

A: 

According to the documentation for Method,

Two method objects are equal if that are bound to the same object and contain the same body.

Calling Object#method and comparing the Method objects that it returns will verify that the methods are equivalent:

m.method(:bar) == m.method(:foo)
bk1e
I was sure I remembered that this didn't work, but I just tried it to confirm and it works consistently in Ruby 1.8, 1.9 and MacRuby. But I still don't see it in RubySpec, so it very likely won't work on an unrelated implementation.
Chuck
Also, in general, methods that merely have identical bodies but aren't copied one from the other are emphatically *not* equal. Proof: `Class.new{def foo() end; def bar() end; puts instance_method(:foo)==instance_method(:bar)}`
Chuck
@Chuck: Thanks for pointing that out. I should have tried it.
bk1e
Also, "returns true on aliased methods" from http://github.com/rubyspec/rubyspec/blob/master/core/method/equal_value_spec.rb + http://github.com/rubyspec/rubyspec/blob/master/core/method/shared/eql.rb seems to cover `m.method(:bar) == m.method(:foo)` when one is an alias of the other.
bk1e