【发布时间】:2010-06-04 14:47:07
【问题描述】:
不久前我问过“How to test obtaining a list of files within a directory using RSpec?”,虽然我得到了一些有用的答案,但我仍然卡住了,因此提出了一个新问题,其中包含有关我正在尝试做什么的更多细节。
我正在编写我的第一个 RubyGem。它有一个模块,其中包含一个类方法,该方法返回一个数组,该数组包含指定目录中的非隐藏文件列表。像这样:
files = Foo.bar :directory => './public'
该数组还包含一个表示有关文件的元数据的元素。这实际上是从文件内容生成的哈希哈希,其想法是即使更改单个文件也会更改哈希。
我已经编写了待处理的 RSpec 示例,但我真的不知道如何实现它们:
it "should compute a hash of the files within the specified directory"
it "shouldn't include hidden files or directories within the specified directory"
it "should compute a different hash if the content of a file changes"
我真的不想让测试依赖于充当夹具的真实文件。如何模拟或存根文件及其内容? gem 实现将使用Find.find,但正如我对另一个问题的答案之一所说,我不需要测试库。
我真的不知道如何编写这些规范,所以非常感谢任何帮助!
编辑:下面的cache 方法是我要测试的方法:
require 'digest/md5'
require 'find'
module Manifesto
def self.cache(options = {})
directory = options.fetch(:directory, './public')
compute_hash = options.fetch(:compute_hash, true)
manifest = []
hashes = ''
Find.find(directory) do |path|
# Only include real files (i.e. not directories, symlinks etc.)
# and non-hidden files in the manifest.
if File.file?(path) && File.basename(path)[0,1] != '.'
manifest << "#{normalize_path(directory, path)}\n"
hashes += compute_file_contents_hash(path) if compute_hash
end
end
# Hash the hashes of each file and output as a comment.
manifest << "# Hash: #{Digest::MD5.hexdigest(hashes)}\n" if compute_hash
manifest << "CACHE MANIFEST\n"
manifest.reverse
end
# Reads the file contents to calculate the MD5 hash, so that if a file is
# changed, the manifest is changed too.
def self.compute_file_contents_hash(path)
hash = ''
digest = Digest::MD5.new
File.open(path, 'r') do |file|
digest.update(file.read(8192)) until file.eof
hash += digest.hexdigest
end
hash
end
# Strips the directory from the start of path, so that each path is relative
# to directory. Add a leading forward slash if not present.
def self.normalize_path(directory, path)
normalized_path = path[directory.length,path.length]
normalized_path = '/' + normalized_path unless normalized_path[0,1] == '/'
normalized_path
end
end
【问题讨论】: