1

Ruby を学んで、Ruby アプリのディレクトリ構造は lib/ と test/ の規則に従います

私のルート ディレクトリには、認証設定ファイルがあり、lib/. File.open('../myconf') として読み取られます。

Rake でテストする場合、作業ディレクトリが lib/ や test/ ではなくルートであるため、ファイルを開くことができません。

これを解決するために、2 つの質問があります: それは可能ですか? 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 ディレクトリにコピーするタスクをセットアップしましたが、作業ディレクトリが 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
4

2 に答える 2

1

そのためにFile.expand_pathメソッドを使用することをお勧めします。(現在のファイル -あなたの場合)にauth.conf基づいて、または必要なものに応じて、ファイルの場所を評価できます。__FILE__lib/a.rbRails.root

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
于 2013-07-18T09:50:19.530 に答える