Reputation: 29
I would like to know how to test in rspec is specific file is deleted. Here is code that I am testing
def check_status
filename = File.join('test', 'status.txt')
File.delete(filename ) if File.exist?(filename)
end
Here is test:
before do
allow(File).to receive(:exist?).and_return(true)
allow(File).to receive(:delete)
end
it {expect(File).to receive(:delete).with("test/status.txt") }
I am getting error
(File (class)).delete("test/status.txt")
expected: 1 time with arguments: ("test/status.txt")
received: 0 times
Could you please help me with this issue. I am sure that my code delete the file, but in tests it receive it 0 times.
Upvotes: 1
Views: 1832
Reputation: 1
updated question
File.delete('status.txt') if File.exist?('status.txt')
Solution
context '#delete' do
it 'deletes the file' do
allow(File).to receive(:exist?).and_return(true)
allow(File).to receive(:delete)
expect(File).to receive(:delete).with("status.txt")
# suppose check_status method is defined in TempClass
delete = TempClass.new
delete.check_status
end
end
Upvotes: 0
Reputation: 27779
From your spec, it appears that you are mocking and stubbing correctly, but you never call check_status
, so the stubs and mocks don't get used. You could change your example to something like:
it 'deletes the file' do
expect(File).to receive(:delete).with("test/status.txt")
MyModel.check_status
end
It would be better still to test this with an actual file, instead of mocks and stubs, so that it also tests that the file is in the correct location, that you have the necessary permissions, etc.
Upvotes: 4