对不起,如果这很简单.我是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"却不是:
().exist?("dummy.yaml") expected: 1 time with arguments: ("dummy.yaml") received: 0 times
那么如何在"File.exist"上进行"重置"?(一个类方法模拟)在我设置它的新期望之前?(..."non_existent.yaml"..)
我用Google搜索并且它产生了:
RSpec::Mocks.proxy_for(your_object).reset
但这给了我:
NoMethodError: undefined method `proxy_for' for RSpec::Mocks:Module
Uri Agassi.. 7
我在文档中的任何地方都找不到这是你应该怎么做的,过去的行为表明这个解决方案将来也可能会改变,但显然这就是你现在可以做到的:
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
如果期望应该针对每个测试运行,因为每个场景中的更改是上下文,您应该考虑使用共享示例:
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
您可能还想询问迈伦是否有更多推荐/记录的解决方案来重置模拟对象...
我在文档中的任何地方都找不到这是你应该怎么做的,过去的行为表明这个解决方案将来也可能会改变,但显然这就是你现在可以做到的:
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
如果期望应该针对每个测试运行,因为每个场景中的更改是上下文,您应该考虑使用共享示例:
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
您可能还想询问迈伦是否有更多推荐/记录的解决方案来重置模拟对象...