【问题标题】:How to stub a ruby method ensuring that it exists in Minitest [duplicate]如何存根 ruby​​ 方法以确保它存在于 Minitest [重复]
【发布时间】:2020-04-07 09:57:36
【问题描述】:

.stubs 上的documentation 相反,我似乎能够存根一个不存在的方法。

考虑以下代码:

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 上的类方法,尽管它不再存在。由于被存根的方法不存在,.stubs 调用是否会失败?

【问题讨论】:

  • 那是你的实际代码吗?您链接的文档有 .stub 方法,而不是 .stubs 方法。我也找不到returns 方法。你在使用一些扩展吗?
  • @arieljuod 由于与stackoverflow.com/q/7211086/3157745 的重复,我实际上将这个问题标记为关闭。我对.stubs 感到困惑,它与.expects 的行为相似,但不应该与完全不同的.stub 混淆(恰好是我正在寻找的东西)。

标签: ruby-on-rails ruby unit-testing minitest


【解决方案1】:

由于被存根的方法不存在,预期的行为是否不会导致 .stubs 调用失败?

不,预期的行为不会失败。这就是为什么。你没有存根方法。您正在对 message 的响应存根。例如,您的代码中有这一行:user.name。这意味着您正在向对象user 发送消息age。教user 处理消息age 的最简单/最常见的方法是确保它有一个名为age 的实例方法。但也有其他方法。您可以使用 method_missing 让用户响应年龄。就 ruby​​ 而言,这同样有效。

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

【讨论】:

  • 您能澄清一下“消息由同名方法处理”是什么意思吗?我可以通过DependencyClass.respond_to?(:method_to_be_stubbed) 验证该方法是否存在,但我认为.stubs 至少会在覆盖之前检查我要覆盖的内容。
  • @Xenyal:比如说,你的代码中有这一行:user.name。这意味着您正在向对象user 发送消息age。教user 处理消息age 的最简单/最常见的方法是确保它有一个名为age 的实例方法。但是,正如我所提到的,您可以让user 使用method_missing 回复age。就 ruby​​ 而言,这同样有效。
  • 如果我们考虑一个使用依赖注入的示例,其中user 是输入,并且我们依赖类的库函数来检索age attr,该怎么办? (例如self.get_user_name(user))另外,我相信类实例方法存根确实会检查实例上是否存在。类方法的行为为何不同?
  • @Xenyal:“我相信类实例方法存根确实会检查实例上是否存在”- 是吗?
  • 我很抱歉,这是我的误解(事实并非如此)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-14
  • 1970-01-01
  • 2022-01-21
  • 2015-11-28
  • 2016-08-04
相关资源
最近更新 更多