gpt4 book ai didi

ruby - 如何使 Dir[] 和 Dir.foreach 以确定的顺序返回结果?

转载 作者:太空宇宙 更新时间:2023-11-03 18:22:31 30 4
gpt4 key购买 nike

我正在尝试使用 Dir[] 和/或使用 Dir.foreach 对目录进行 glob:

files = Dir["#{options[:dir]}/**/*"].reject { |file| File.directory?(file) }
puts files.map{|filename| filename.join("\n")

和:

def print_tree(dir = ".", nesting = 0)
Dir.foreach(dir) do |entry|
next if entry =~ /^\.{1,2}/ # Ignore ".", "..", or hidden files
puts "| " * nesting + "|-- #{entry}"
if File.stat(d = "#{dir}#{File::SEPARATOR}#{entry}").directory?
print_tree(d, nesting + 1)
end
end
end

我正在尝试使用 Cucumber and Aruba 进行测试.这是我的 listing_files.feature 中的内容:

When I run `poet ls`
Then the output should contain exactly:
"""
foo/bar/conf1
foo/conf2.disabled

"""

和:

Then the output should contain exactly:
"""
|-- foo
| |-- bar
| | |-- conf1
| |-- conf2.disabled

"""

在我的本地机器上测试工作 (OSX) 正常,但我在 Travis 上遇到这个故障:

expected: "foo/bar/conf1\nfoo/conf2.disabled\n"
got: "foo/conf2.disabled\nfoo/bar/conf1\n" (using ==)

显然,返回结果的顺序在所有系统上都不相同。这是 documented behavior对于 1.9.3 和 2.0:

Note that case sensitivity depends on your system (so File::FNM_CASEFOLD is ignored), as does the order in which the results are returned.

但这使得测试目录列表成为一场噩梦。我可以以某种方式强制执行命令吗?或者,如果没有,是否有最佳实践来综合测试此类内容?

最佳答案

您始终可以在返回 Dir[] 调用的结果之前对其进行排序:

def print_tree(dir = ".", nesting = 0)
Dir.entries(dir).sort.each do |entry|
# the rest is the same...
end
end

或者,如果您有两个目录列表数组,请在比较它们之前在测试中对每个数组进行排序。

此外,如果您使用的是 RSpec,则可以使用 =~ 运算符期望数组内容而不是顺序/内容:

arr1 = Dir['*.whatever']
arr2 = some_method_that_gets_the_dir_listing()
arr2.should =~ arr1

在 Test::Unit 中,同样可以使用 assert_same_elements

关于ruby - 如何使 Dir[] 和 Dir.foreach 以确定的顺序返回结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15935370/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com