你如何在 chefspec 中模拟一个函数调用,用于用另一个 class 扩展的对象实例
How do you mock a function call in chefspec for an object instance extended with another class
我是单元测试和 Chefspec 的新手。我正在尝试 mock/intercept 来自依赖库的配方中的函数调用
图书馆
module Helper
def do_something_useful
return "http://example.com/file.txt"
end
end
食谱
remote_file '/save/file/here' do
extend Helper
source do_something_useful
end
我试过以下方法:
Chefspec
allow_any_instance_of(Chef::Resource::RemoteFile).to receive(:do_something_useful).and_return('foobar')
allow_any_instance_of(Chef::Resource).to receive(:do_something_useful).and_return('foobar')
我也试过用 double 模拟:
helper = double
Helper.stub(:new).and_return(helper)
allow(helper).to receive(:do_something_useful).and_return('foobar')
失败 uninitialized constant Helper
太棒了,这是一个有趣的案例,其中 extend
正在覆盖模拟方法。所以我们可以只使用 extend
来驱动东西:
before do
allow_any_instance_of(Chef::Resource::RemoteFile).to receive(:extend) do |this, m|
Module.instance_method(:extend).bind(this).call(m)
allow(this).to receive(:do_something_useful).and_return('foobar')
end
end
这就像 800% 的魔法,你可能不应该使用它,但它在我的小测试环境中确实有效。
我是单元测试和 Chefspec 的新手。我正在尝试 mock/intercept 来自依赖库的配方中的函数调用
图书馆
module Helper def do_something_useful return "http://example.com/file.txt" end end
食谱
remote_file '/save/file/here' do extend Helper source do_something_useful end
我试过以下方法:
Chefspec
allow_any_instance_of(Chef::Resource::RemoteFile).to receive(:do_something_useful).and_return('foobar') allow_any_instance_of(Chef::Resource).to receive(:do_something_useful).and_return('foobar')
我也试过用 double 模拟:
helper = double Helper.stub(:new).and_return(helper) allow(helper).to receive(:do_something_useful).and_return('foobar')
失败
uninitialized constant Helper
太棒了,这是一个有趣的案例,其中 extend
正在覆盖模拟方法。所以我们可以只使用 extend
来驱动东西:
before do
allow_any_instance_of(Chef::Resource::RemoteFile).to receive(:extend) do |this, m|
Module.instance_method(:extend).bind(this).call(m)
allow(this).to receive(:do_something_useful).and_return('foobar')
end
end
这就像 800% 的魔法,你可能不应该使用它,但它在我的小测试环境中确实有效。