Rspec:如何测试文件操作和文件内容 [英] Rspec: how to test file operations and file content

查看:174
本文介绍了Rspec:如何测试文件操作和文件内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



  File.openfilename,wdo | file | 
file.write(text)
end

我想测试这个代码通过rspec。这样做的最佳做法是什么?

解决方案

我会建议使用 StringIO 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:如何测试文件操作和文件内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆