I created a class that I want to bind to a file descriptor, and close it when the GC-ed instance.
I created a class that looks something like this:
class DataWriter
def initialize(file)
@file = File.open(file, 'wb')
ObjectSpace.define_finalizer(self, self.class.finalize(@file))
end
def write(line)
@file.puts(line)
@file.flush
end
def self.finalize(file)
proc { file.close; p "file closed"; p file.inspect}
end
end
Then I tried to test the destructor method as follows:
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
When performing this test, even though the "file is closed" is printed with the file. inspect, the test fails with the following output:
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
source
share