问题描述
File.openfilename,wdo | file |
file.write(text)
end
我想测试这个代码通过rspec。这样做的最佳做法是什么?
我会建议使用 StringIO $ c $为此,并确保你的SUT接受一个流来写入而不是文件名。这样,可以使用不同的文件或输出(更可重复使用),包括字符串IO(适用于测试)。因此,在您的测试代码(假设您的SUT实例是
sutObject
并且序列化程序被命名为 writeStuffTo
:
testIO = StringIO.new
sutObject.writeStuffTo testIO
testIO.string.should ==Hello,world!
字符串IO的行为就像一个打开的文件,所以如果代码已经可以和File对象一起工作,它就可以和StringIO一起工作。 b
In my app I have such code:
File.open "filename", "w" do |file|
file.write("text")
end
I want to test this code via rspec. What is the best practices for doing this?
I would suggest using StringIO
for this and making sure your SUT accepts a stream to write to instead of a filename. That way, different files or outputs can be used (more reusable), including the string IO (good for testing)
So in your test code (assuming your SUT instance is sutObject
and the serializer is named writeStuffTo
:
testIO = StringIO.new
sutObject.writeStuffTo testIO
testIO.string.should == "Hello, world!"
String IO behaves like an open file. So if the code already can work with a File object, it will work with StringIO.
这篇关于Rspec:如何测试文件操作和文件内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!