1
votes

Learning Ruby, my Ruby app directory structure follows the convention with lib/ and test/

in my root directory I have a authentication config file, that I read from one of the classes in lib/. It is read as File.open('../myconf').

When testing with Rake, the file open doesn't work since the working directory is the root, not lib/ or test/.

In order to solve this, I have two questions: is it possible, and should I specify rake working directory to test/ ? should I use different file discovery method? Although I prefer convention over config.

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

Trying to invoke with Rake. I did setup a task to copy the auth.conf to the test directory, but turns out that the working dir is above test/.

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

Rakefile

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
2
please add the code that fails + stack traceKonstantin Rudy
@roody ok, please see my edit.H.Rabiee
thanks, have added a responceKonstantin Rudy

2 Answers

1
votes

You're probably getting that error because you're running rake from the projects root directory, which means that the current working directory will be set to that directory. This probably means that the call to File.open("../auth.conf") will start looking one directory up from your current working directory.

Try specifying the absolute path to the config file, for example something like this:

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

Btw, I took the liberty of changing openFile -> open_file, since that's more consistent with ruby coding conventions.

1
votes

I recommend using File.expand_path method for that. You can evaluate auth.conf file location based on __FILE__(current file - lib/a.rb in your case) or Rails.root depending on what you need.

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