7

How to test if if method has an alias?

Let's say we have

Class Test
  class << self
    def a;end
    alias :b :a
  end
end

so far I came up with idea to write this spec:

it { expect(Test.b).to receive(:a) }

but I believe there is better solution. Any ideas?

Filip Bartuzi
  • 5,711
  • 7
  • 54
  • 102

4 Answers4

18

You can use Object#method.

Test.method(:b) == Test.method(:a)
oldergod
  • 15,033
  • 7
  • 62
  • 88
9

You can use:

expect(obj.method(:method)).to eq(obj.method(:alias))
Arnold Roa
  • 7,335
  • 5
  • 50
  • 69
7

oldergod's answer works in most scenarios:

Test.method(:b) == Test.method(:a)

Unfortunately it doesn't work in Ruby 2.3+ when the two methods have different owners (e.g. when the method is defined in a module, and the alias is defined in a class that includes the module). This is because the behavior of Method#== changed in Ruby 2.3:

If owners of methods are different, the behavior of super is different in the methods, so Method#== should not return true for the methods.

If you find yourself in this situation, where you want to test that two methods are aliases of each other but they have different owners, you can use Method#original_name or Method#source_location instead:

Test.method(:b).original_name == Test.method(:a).original_name
Test.method(:b).source_location == Test.method(:a).source_location
Jeff Manian
  • 81
  • 1
  • 4
-4

You can set a result to your function to check if result is same.

def a
  return 'test string'
end

then it { expect(Test.b).to eq(Test.a) }

is it ok?

dddd1919
  • 868
  • 5
  • 13