2013-07-17 49 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