簡體   English   中英

配置位置紅寶石並使用rake進行單元測試

[英]config location ruby and using rake for unit test

學習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

測試/ 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

您可能會收到該錯誤,因為您是從項目根目錄運行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編碼約定更加一致。

我建議為此使用File.expand_path方法。 您可以根據需要評估lib/a.rb __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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM