Reputation: 404
I've created a class that creates a new text file. When I try to compare it with an existing file it seems that RSpec thinks the created file is empty.
expect(open @expected).to eq(open @result)
The result:
(compared using ==)
Diff:
@@ -1,2 +1,2 @@
-[]
+["The expected output\n"]
Here's the code that creates the file:
FileUtils.touch out_path
target = File.new out_path, 'w+'
File.open(in_path, "r") do |file_handle|
file_handle.each_line do |line|
target.puts line
end
end
Upvotes: 0
Views: 134
Reputation: 121000
You do not flush the file content to disk. Ruby will flush it itself, but whenever it decides to. To assure that the file content is flushed, one should use the block variant with File#open
instead of File.new
:
File.open(out_path, 'w+') do |target|
File.open(in_path, "r") do |file_handle|
file_handle.each_line do |line|
target.puts line
end
end
end # here file is flushed
With File#new
you have an option to flush
the content explicitly or do implicitly by calling close
.
Hope it helps.
Upvotes: 1