2013-07-17 50 views
1

學習Ruby,我的Ruby應用程序的目錄結構遵循慣例 以lib /和測試/配置位置紅寶石和使用耙的單元測試

在我的根目錄

我有一個認證配置文件,使我從一個讀lib /中的類。它被讀作File.open('../ myconf')。

使用Rake進行測試時,打開的文件不起作用,因爲工作目錄是根目錄,而不是lib /或test /。

爲了解決這個問題,我有兩個問題: 是否可能,並且我應該指定rake工作目錄來測試/? 我應該使用不同的文件發現方法嗎?雖然我更喜歡約定而不是配置。

LIB/A.rb

class A 
def openFile 
    if File.exists?('../auth.conf') 
     f = File.open('../auth.conf','r') 
... 

    else 
     at_exit { puts "Missing auth.conf file" } 
     exit 
    end 
end 

測試/ testopenfile.rb

require_relative '../lib/A' 
require 'test/unit' 

class TestSetup < Test::Unit::TestCase 

    def test_credentials 

     a = A.new 
     a.openFile #error 
     ... 
    end 
end 

試圖用Rake來調用。我確實設置了一個任務來將auth.conf複製到測試目錄,但是結果是工作目錄在test /之上。

> rake 
cp auth.conf test/ 
/.../.rvm/rubies/ruby-1.9.3-p448/bin/ruby test/testsetup.rb 
Missing auth.conf file 

Rake文件

task :default => [:copyauth,:test] 

desc "Copy auth.conf to test dir" 
     task :copyauth do 
       sh "cp auth.conf test/" 
     end 

desc "Test" 
     task :test do 
       ruby "test/testsetup.rb" 
     end 
+0

請添加代碼失敗+堆棧跟蹤 – roody

+0

@roody ok,請參閱我的編輯。 – Rabiees

+0

謝謝,已添加應答 – roody

回答

1

,因爲你正在運行從項目的根目錄,這意味着當前的工作目錄將被設置到該目錄rake你可能會得到這個錯誤。這可能意味着對File.open("../auth.conf")的調用將從當前工作目錄開始查找一個目錄。

嘗試指定的絕對路徑的配置文件,例如像這樣:

class A 
    def open_file 
    path = File.join(File.dirname(__FILE__), "..", "auth.conf") 
    if File.exists?(path) 
     f = File.open(path,'r') 
     # do stuff... 
    else 
     at_exit { puts "Missing auth.conf file" } 
    exit 
    end 
end 

順便說一句,我把改變openFile的自由 - >open_file,因爲這是用Ruby編碼慣例更加一致。

1

我建議使用File.expand_path方法。您可以根據您的需要,根據__FILE__(當前文件 - lib/a.rb)或Rails.root評估auth.conf文件位置。

def open_file 
    filename = File.expand_path("../auth.conf", __FILE__) # => 'lib/auth.conf' 

    if File.exists?(filename) 
    f = File.open(filename,'r') 
    ... 
    else 
    at_exit { puts "Missing auth.conf file" } 
    exit 
    end 
end