抱歉,如果这很简单。我对 ruby 和 rspec 都是新手,似乎 rspec 是一个非常“晦涩”的世界(特别是来自 .net 背景时)。
在我的“规范”中,我有:
before(:each) do
expect(File).to receive(:exist?).with("dummy.yaml").and_return (true)
end
这对于我所有的“示例”都适用,除了我希望它返回 false 的示例。
expect(File).to receive(:exist?).with("non_existent.yaml").and_return (false)
这显然失败了我的测试,因为尽管满足了“non_existent.yaml”期望,但“dummy.yaml”却没有:
(<File (class)>).exist?("dummy.yaml")
expected: 1 time with arguments: ("dummy.yaml")
received: 0 times
那么我怎样才能对“File.exist”进行“重置”呢? (类方法模拟)在我设置新的期望之前? (...“non_existent.yaml”..)
我用谷歌搜索,结果是:
RSpec::Mocks.proxy_for(your_object).reset
但这给了我:
NoMethodError:
undefined method `proxy_for' for RSpec::Mocks:Module
我在文档中找不到任何地方可以说明您应该如何执行此操作,并且过去的行为表明该解决方案将来也可能会发生变化,但显然这是您当前可以执行的操作:
RSpec::Mocks.space.proxy_for(your_object).reset
不过,我会遵循 @BroiSatse 的评论,并考虑重新设计测试,旨在将期望从before
堵塞。这before
正如你所说,块是用于设置的,而设置是一个非常奇怪的放置期望的地方。
我不确定你是如何想到这个设计的,但我可以建议两种可能的替代方案:
-
如果测试很简单,并且无论如何都会工作,那么您应该创建一个具有这一明确期望的测试,同时将其存根用于其他测试:
before(:each) do
allow(File).to receive(:exist?).with("dummy.yaml").and_return (true)
end
it "asks if file exists" do
expect(File).to receive(:exist?).with("dummy.yaml").and_return (true)
# do the test...
end
-
如果期望应该针对每个测试运行,因为每个场景中的变化是context,你应该考虑使用分享的例子 https://www.relishapp.com/rspec/rspec-core/docs/example-groups/shared-examples:
shared_examples "looking for dummy.yaml" do
it "asks if file exists" do
expect(File).to receive(:exist?).with("dummy.yaml").and_return (true)
# do the test...
end
end
it_behaves_like "looking for dummy.yaml" do
let(:scenario) { "something which sets the context"}
end
您可能还想问迈伦 https://github.com/rspec/rspec-mocks/issues/new如果有更推荐/记录的解决方案来重置模拟对象......
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)