RSpec 测试(Ruby on Rails)上下文中的“StringIO”是什么?

What is `StringIO` in the context of RSpec testing (Ruby on Rails)?

Rails Ruby 中的 StringIO 是什么?

我正在尝试理解另一个引用 StringIO 的 SO 答案,但它超出了我的理解范围。

I would suggest using StringIO for this and making sure your SUT accepts a stream to write to instead of a filename.

testIO = StringIO.new
sutObject.writeStuffTo testIO 
testIO.string.should == "Hello, world!"

来源:Rspec: how to test file operations and file content

Ruby-doc.org

Pseudo I/O on String object.

来源:http://ruby-doc.org/stdlib-1.9.3/libdoc/stringio/rdoc/StringIO.html)

Robots.thoughtbot

This is common in tests where we might inject a StringIO instead of reading an actual file from disk.

来源:https://robots.thoughtbot.com/io-in-ruby#stringio

我的情况:

File.open("data.dat", "wb") {|f| f.write(snapshot)}

在我的应用程序中,我想测试以上内容,但我仍然对 StringIO 如何应用于实施 RSpec 测试感到困惑。

StringIO经验的人能给点指导吗?

StringIO 是 IO 对象的基于字符串的替代品。它的作用与文件相同,但它作为字符串保存在内存中。

对于你的情况,我认为它并不适用。至少不是您当前的代码。那是因为您有 File.open 调用创建了一个 IO 对象并立即用它做一些事情。

例如,如果你有这样的事情:

def write_data(f)
  f.write(snapshot)
end

# your code would be
f = File.open("data.dat", "wb")
write_data(f)

# test would be
testIO = StringIO.new
write_data(testIO)
testIO.string.should == "Hello, world!"