【问题标题】:How to test method alias ruby如何测试方法别名 ruby
【发布时间】:2014-09-17 06:22:01
【问题描述】:

如何判断方法是否有别名?

假设我们有

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

到目前为止,我想出了编写此规范的想法:

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

但我相信有更好的解决方案。有什么想法吗?

【问题讨论】:

  • 是否应该测试方法别名? github.com/rspec/rspec-core/issues/1962
  • @chemturion 提出这个问题多年后,多年来在 RSpec 中编写了无数测试,我可以肯定地说你不应该 :)

标签: ruby-on-rails ruby ruby-on-rails-4 rspec


【解决方案1】:

您可以使用Object#method

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

【讨论】:

  • Test 实例方法上使用它:Test.new.method(:b) == Test.new.method(:a)
【解决方案2】:

你可以使用:

expect(obj.method(:method)).to eq(obj.method(:alias))

【讨论】:

    【解决方案3】:

    oldergod 的回答适用于大多数情况:

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

    不幸的是,当 这两个方法拥有不同的所有者(例如,当方法定义在模块中,而别名定义在包含该模块的类中时,它在 Ruby 2.3+ 中不起作用)。这是因为the behavior of Method#== changed in Ruby 2.3:

    如果方法的所有者不同,super 的行为在方法中是不同的,因此 Method#== 不应为方法返回 true。

    如果您发现自己处于这种情况,您想测试两个方法是否是彼此的别名但它们有不同的所有者,您可以改用Method#original_nameMethod#source_location

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

    【讨论】:

    • 我发现它在 Ruby 2.7 中根本不起作用。
    【解决方案4】:

    你可以给你的函数设置一个结果来检查结果是否相同。

    def a
      return 'test string'
    end
    

    那么 它{期望(Test.b).to eq(Test.a)}

    还好吗?

    【讨论】:

    • 相同的结果并不意味着它是一个别名。
    猜你喜欢
    • 2015-01-31
    • 2019-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-10
    • 1970-01-01
    • 1970-01-01
    • 2015-01-07
    相关资源
    最近更新 更多