2013-04-10 27 views
1

我想一個glob的目錄,與Dir[]和/或Dir.foreach如何使Dir []和Dir.foreach以確定性順序返回結果?

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)精細的測試,但我得到特拉維斯此故障:

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

顯然,所有系統中返回結果的順序都不相同。這是documented behavior爲1.9.3和2.0:

注意大小寫敏感性取決於你的系統(使文件:: FNM_CASEFOLD被忽略), 一樣在返回結果的順序。

這使得測試目錄列出了一場噩夢。我可以以某種方式強制下單嗎?或者,如果沒有,是否有一個最佳實踐來測試這樣的綜合性?或者

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

,如果你比較之前有目錄列表兩個數組,每個種類的測試:

+1

請告訴我們你正在使用的代碼。只有產出是不夠的。 –

+0

@RubyLovely你是對的,我更新了問題! – awendt

回答

3

你總是可以在Dir[]調用的結果返回之前排序。使用assert_same_elements

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

在測試::單位,同樣可以做到:

另外,如果你使用的RSpec您可以通過使用=~運營商期望在數組的內容,而不是爲了/內容

+0

我試圖用Cucumber + Aruba一體測試這個。我已經更新了相應的問題。對困惑感到抱歉。 – awendt

+1

我認爲在系統中保持輸出一致非常重要,因此我建議在開始構建'print_tree'輸出之前對目錄輸出進行排序,就像我先建議的那樣 - 我更新了我的答案以向您展示。 – rusty

+0

這很有效,非常感謝!跨系統的一致輸出的好處。我現在意識到:這不是關於測試,而是關於一般軟件的更多信息。 – awendt

0

如果你不關心順序,你可以隨時使用include匹配用圖示來解開你的陣列

[1,2,3,4,5].should include(*[5,2,4,1,3]) 
+0

我試圖用Cucumber + Aruba一體測試。我已經更新了相應的問題。對困惑感到抱歉。 – awendt

相關問題