如何对红宝石方法进行存根,以确保它存在于Minitest [duplicate]中

问题描述 投票:0回答:1

documentation上的.stubs相反,看来我能够对不存在的方法进行存根。

考虑以下代码:

class DependencyClass
  def self.method_to_be_stubbed
    'hello'
  end
end

class TestMethodClass
  def self.method_being_tested
    DependencyClass.method_to_be_stubbed
  end
end

class StubbedMissingMethodTest < ActiveSupport::TestCase
  test '#method_being_tested should return value from stub' do
    assert_equal 'hello', TestMethodClass.method_being_tested

    DependencyClass.stubs(:method_to_be_stubbed).returns('goodbye')

    assert_equal 'goodbye', TestMethodClass.method_being_tested
  end
end

在此示例中,DependencyClass.stubs(:method_to_be_stubbed).returns('goodbye')可以正常工作,因为#method_to_be_stubbed上存在DependencyClass。但是,如果我将#method_to_be_stubbed更改为DependencyClass的类实例方法,如下所示:

class DependencyClass
  def method_to_be_stubbed
    'hello'
  end
end

class StubbedMissingMethodTest < ActiveSupport::TestCase
  test '#method_being_tested should return value from stub' do
    assert_equal 'hello', TestMethodClass.method_being_tested

    # despite the method not existing on the class,
    # instead on the instance - yet it still works?
    DependencyClass.stubs(:method_to_be_stubbed).returns('goodbye')

    assert_equal 'goodbye', TestMethodClass.method_being_tested
  end
end

我的#method_to_be_stubbed存根在DependencyClass上保留了class方法,尽管它不再存在。因为被存根的方法不存在,所以预期的行为不是.stubs调用失败的原因吗?

ruby-on-rails ruby unit-testing minitest
1个回答
1
投票

难道不是因为.stubs调用失败的预期行为,因为被存根的方法不存在?

不,预期的行为不会失败。这就是为什么。您没有在使用方法。您正在对message进行响应。例如,您的代码中包含以下行:user.name。这意味着您正在向对象age发送消息user。教user处理消息age的最简单/最常见的方法是确保它具有称为age的实例方法。但是,还有其他方法。您可以使用method_missing来使用户响应年龄。就红宝石而言,这同样有效。

因此,最小检验在这里检查方法的存在是错误的。

© www.soinside.com 2019 - 2024. All rights reserved.