Calling stub(:method)
will stub the method on the object you called it on. So your call to File.stub(:new)
will stub all calls to File.new (class method). The call to file.stub(:close)
will stub all calls to file.close but only on the instance you called stub on
If you want to stub all calls to any instance of File you can:
- use any_instance
or you can stub File.new to make it only return file objects with a stubbed close, like you do in:
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. 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