我应该使用什么策略来对 ruby (rspec) 中的文件进行单元测试?
我有一个 ruby 方法,可以逐行处理一个非常大的文件(即我无法将文件加载到内存中),如下所示:
def process_file
file = File.new(@@data_file, "r")
while (line = file.gets)
{ do something with the line } ...
end
file.close
return "upload complete"
end
根据最佳实践,我不希望此方法对文件系统。我以前使用过存根,但我不确定在这里如何使用它。我想我会使用相当于:
file = File.stub!(:new).and_return({something})
我只是不确定 {something} 是什么。
我正在使用 rspect,如有任何帮助,将不胜感激。谢谢。
I've got a ruby method which processes a very large file line-by-line (ie I cannot load the file into memory) like the following:
def process_file
file = File.new(@@data_file, "r")
while (line = file.gets)
{ do something with the line } ...
end
file.close
return "upload complete"
end
As per best practices, I do not want this this method to have any reliance on the filesystem. I've used stubs before, but I'm not sure how I would go about using it here. I would imagine I would use something equivalent to:
file = File.stub!(:new).and_return({something})
I'm just not sure what {something} is.
I am using rspect and Any assistance would be appreciated. Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您始终可以检查是否调用了正确的方法,至少是之后的
close()
。我认为这是 I/O 最常见的错误。You could always check if you call proper methods, at least the
close()
after. I think that's the most often error with i/o.您可能想查看 MockFS,它模拟了文件系统的操作。
You might want to look at MockFS, which mocks out the operation of the filesystem.
我认为这里不需要单元测试。您是否担心创建文件/关闭文件会在 Ruby 的未来版本中被破坏?不是的,不用担心。
让 Ruby 开发人员担心对其平台特定的文件 IO 例程进行单元测试。您应该担心对您的算法进行单元测试,特别是那些关键且复杂的算法(即,如果您不小心,很容易损坏)。
也就是说,您可能应该只将一个块传递给构造函数。这确保了当块退出时文件将为您关闭,并且更惯用。
I don't think that a unit test is called for here. Are you afraid that, somehow, creating files/closing files is going to be broken in some future version of Ruby? It's not, don't worry.
Let the Ruby devs worry about unit testing their platform specific file IO routines. You should worry about unit testing your algorithms, and specifically those algorithms which are critical and complex (i.e., prone to breakage if you're not careful).
That said, you should probably just pass a block to the constructor. This ensures that the file will be closed for you when the block exits and is more idiomatic.