【发布时间】: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