简体   繁体   English

如何使用RSpec测试获取目录中的文件列表?

[英]How to test obtaining a list of files within a directory using RSpec?

I'm pretty new to the world of RSpec. 我对RSpec的世界很陌生。 I'm writing a RubyGem that deals with a list of files within a specified directory and any sub-directories. 我正在写一个RubyGem,它处理指定目录和任何子目录中的文件列表。 Specifically, it will use Find.find and append the files to an Array for later output. 具体来说,它将使用Find.find并将文件附加到数组以供以后输出。

I'd like to write a spec to test this behaviour but don't really know where to start in terms of faking a directory of files and stubbing Find.find etc. This is what little I have so far: 我想编写一个规范来测试此行为,但实际上不知道从伪造文件目录和对Find.find等进行存根的Find.find 。这是我到目前为止所没有的:

it "should return a list of files within the specified directory" do
end

Any help much appreciated! 任何帮助,不胜感激!

您可以使用fakeFS gem。

I don't think you need to test the library, but if you have a method like 我认为您不需要测试库,但是如果您有类似的方法

def file_names
  files = []
  Find.find(Dir.pwd){|file| files << file}
  ........
end

you can stub the find method to return a list of files like so 您可以存根find方法以返回文件列表,如下所示

it "should return a list of files within the specified directory" do
  Find.stub!(:find).and_return(['file1', 'file2'])
  @object.file_names
end

or if you want to set the expectation then you can do 或者,如果您要设定期望,则可以

it "should return a list of files within the specified directory" do
  Find.should_receive(:find).and_return(['file1', 'file2'])
  @object.file_names
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM