来自文档
rspec-mocks提供了两个方法,
allow_any_instance_of和expect_any_instance_of,它们将允许您对类的任何实例进行存根或模拟。它们被用于代替允许或期望:
allow_any_instance_of(Widget).to receive(:name).and_return("Wibble")对于使用Minitest的类的所有实例,是否有类似于此特性的模拟方法?
发布于 2020-06-17 17:15:47
根据Minitest文档,您只能模拟单个实例。
https://github.com/seattlerb/minitest#mocks-
在看不到整个代码的情况下,很难判断,但您的体系结构可能会得到改进。例如,您可以使用依赖项注入来避免allow_any_instance_of,还可以使类更易于扩展。
而不是做
class Foo
def initialize
@widget = Widget.new
end
def name
widget.name
end
end做你的测试
it "does expect name" do
allow_any_instance_of(Widget).to receive(:name).and_return("Wibble")
Foo.new.name
end您可以像这样注入小部件类
class Foo
def initialize(widget_class = Widget)
@widget = widget_class.new
end
def name
widget.name
end
end在你的规范里
it "does expect name" do
widget = double()
widget.stub(:name) { 'a name' }
foo = Foo.new(widget)
expect(foo.name).to eq('a name')
end该代码现在遵循开放-封闭原则,并且更易于扩展.但是很难在没有看到代码的情况下判断这是否是一个可行的解决方案。
在这里https://sourcediving.com/testing-external-dependencies-using-dependency-injection-ad06496d8cb6的一篇博客文章中总结了这一点
https://stackoverflow.com/questions/62430417
复制相似问题