作者热门文章
- xml - AJAX/Jquery XML 解析
- 具有多重继承的 XML 模式
- .net - 枚举序列化 Json 与 XML
- XML 简单类型、简单内容、复杂类型、复杂内容
我创建了一个类,我想将其卡在文件描述符上并在实例被 GC 处理时将其关闭。
我创建了一个看起来像这样的类:
class DataWriter
def initialize(file)
# open file
@file = File.open(file, 'wb')
# create destructor
ObjectSpace.define_finalizer(self, self.class.finalize(@file))
end
# write
def write(line)
@file.puts(line)
@file.flush
end
# close file descriptor, note, important that it is a class method
def self.finalize(file)
proc { file.close; p "file closed"; p file.inspect}
end
end
然后我尝试像这样测试析构函数方法:
RSpec.describe DataWriter do
context 'it should call its destructor' do
it 'calls the destructor' do
data_writer = DataWriter.new('/tmp/example.txt')
expect(DataWriter).to receive(:finalize)
data_writer = nil
GC.start
end
end
end
运行此测试时,即使“file closed”与 file.inspect 一起打印,测试也会失败并输出以下内容:
1) DataWriter it should call its destructor calls the destructor
Failure/Error: expect(DataWriter).to receive(:finalize)
(DataWriter (class)).finalize(*(any args))
expected: 1 time with any arguments
received: 0 times with any arguments
# ./spec/utils/data_writer_spec.rb:23:in `block (3 levels) in <top (required)>'
最佳答案
finalize
在 initialize
中被调用,返回 proc,并且再也不会被调用,所以你不能期望它在 finalization 时被调用。它是在实例完成时调用的 proc。要检查这一点,让 proc 调用一个方法而不是自己完成工作。这通过了:
class DataWriter
# initialize and write same as above
def self.finalize(file)
proc { actually_finalize file }
end
def self.actually_finalize(file)
file.close
end
end
RSpec.describe DataWriter do
context 'it should call its destructor' do
it 'calls the destructor' do
data_writer = DataWriter.new('/tmp/example.txt')
expect(DataWriter).to receive(:actually_finalize)
data_writer = nil
GC.start
end
end
end
关于ruby - 您如何测试是否会调用 Ruby 析构函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39217681/
我是一名优秀的程序员,十分优秀!