与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
调用失败的原因吗?
难道不是因为.stubs调用失败的预期行为,因为被存根的方法不存在?
不,预期的行为不会失败。这就是为什么。您没有在使用方法。您正在对message进行响应。例如,您的代码中包含以下行:user.name
。这意味着您正在向对象age
发送消息user
。教user
处理消息age
的最简单/最常见的方法是确保它具有称为age
的实例方法。但是,还有其他方法。您可以使用method_missing来使用户响应年龄。就红宝石而言,这同样有效。
因此,最小检验在这里检查方法的存在是错误的。