RSpec 认为创建的文件是空的

RSpec thinks created file is empty

我创建了一个 class 来创建一个新的文本文件。当我尝试将它与现有文件进行比较时,RSpec 似乎认为创建的文件是空的。

expect(open @expected).to eq(open @result)

结果:

(compared using ==)

   Diff:
   @@ -1,2 +1,2 @@
   -[]
   +["The expected output\n"]

这是创建文件的代码:

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

您没有将文件内容刷新到磁盘。 Ruby 会自行刷新它,但只要它决定这样做。为了确保文件内容被刷新,应该使用带有 File#open 而不是 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

有了 File#new,您可以选择 flush the content explicitly or do implicitly by calling close

希望对您有所帮助。