【问题标题】:config location ruby and using rake for unit test配置位置 ruby​​ 并使用 rake 进行单元测试
【发布时间】:2013-07-18 17:50:19
【问题描述】:

学习 Ruby,我的 Ruby 应用目录结构遵循约定 使用 lib/ 和 test/

在我的根目录中,我有一个身份验证配置文件,我从 lib/ 中的一个类中读取该文件。它读作 File.open('../myconf')。

使用 Rake 进行测试时,打开的文件不起作用,因为工作目录是根目录,而不是 lib/ 或 test/。

为了解决这个问题,我有两个问题: 有可能吗,我应该指定 rake 工作目录来 test/ 吗? 我应该使用不同的文件发现方法吗?虽然我更喜欢约定而不是配置。

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

test/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

耙文件

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

【问题讨论】:

  • 请添加失败的代码+堆栈跟踪
  • @roody 好的,请看我的编辑。
  • 谢谢,已添加回复

标签: ruby rake


【解决方案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​​ 编码约定。

【讨论】:

    【解决方案2】:

    我建议为此使用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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-28
      • 2023-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多