2016-05-30 81 views
0

Ruby on Rails中的StringIO是什么?什么是RSpec测试(Ruby on Rails)环境中的`StringIO`?

我想了解另一个SO回答引用StringIO,但它在我的头上。

我会建议使用StringIO为此,并确保您的SUT 接受流写入而不是文件名。

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

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

Ruby-doc.org

伪I /字符串对象O对。

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

Robots.thoughtbot

这是在测试中常见的,我们可能会注入一个StringIO的,而不是 从磁盘读取实际的文件。

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

我的情况:

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

在我的应用程序要测试上面,但我仍然感到困惑如何StringIO适用于实施一个RSpec测试。

有没有人在StringIO有一些经验给一些指导?

回答

2

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

在你的情况下,我不认为它是真的适用。至少不是用你当前的代码。这是因为你有创建一个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!"