简体   繁体   English

Ruby rspec中的存根和模拟

[英]Stubbing and mocking in Ruby rspec

I think I understand that is going on here, but I'd like to make sure. 我想我知道这里正在发生,但我想确定一下。

There is some code that needs unit testing with the File methods stubbed out: 有一些需要使用File方法进行单元测试的代码:

temp = File.new(uri.path)
@path = Rails.root.to_s + "/tmp/" +uri.path.split("/").last
File.open(@path, "w"){|f| f.write(temp.read)} if File.exists(temp)
temp.close

The unit test has: 单元测试具有:

file = mock(File)
File.stub(:new).and_return(file)
File.stub(:open).and_return(file)
file.stub(:close)

I'm guessing the difference between File.stub and file.stub is that File.stub will stub the method on the File class, whereas file.stub ( file is a mock File object) will stub any method on a File object? 我猜的区别File.stubfile.stub是, File.stub将存根上的文件类中的方法,而file.stubfile是一个模拟File对象)将存根上的任何方法File对象吗?

Calling stub(:method) will stub the method on the object you called it on. 调用stub(:method)会将stub(:method)存根到调用它的对象上。 So your call to File.stub(:new) will stub all calls to File.new (class method). 因此,您对File.stub(:new)调用将使对File.new的所有调用都存根(类方法)。 The call to file.stub(:close) will stub all calls to file.close but only on the instance you called stub on file.stub(:close) 调用将对所有对file.close的调用进行存根,但仅在您调用stub的实例上

If you want to stub all calls to any instance of File you can: 如果要对所有对File的任何实例的调用都存根,则可以:

  1. use any_instance 使用any_instance
  2. or you can stub File.new to make it only return file objects with a stubbed close, like you do in: 或者您可以对File.new进行存根处理,使其仅返回已存根关闭的文件对象,就像在以下操作中那样:

     File.stub(:new).and_return(file) File.stub(:open).and_return(file) 

Please be aware that in case 2 every call to File.new after that will return the same instance . 请注意,在情况2中,此后每次对File.new的调用都将返回相同的实例 In case that's not what you want you can always hand a block to stub, where you can provide a substitute for the stubbed metod 如果这不是您想要的,您可以随时将一个块交给存根,在这里您可以替代存根的方法

Your understanding is right. 您的理解是正确的。

File.stub(:new)

stubs the call new on the class File 在类File new的调用

file.stub(:close)

stubs the call close on file object file对象调用close

In your case, you can also do 就您而言,您也可以

file = mock(File, :close => nil) #this will create a mocked object that responds with nil when close is called

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM