1

I'm doing some unit testing, and some of the code is checking to see if files exist based on the relative path of the currently-executing script by using the FILE variable. I'm doing something like this:

if File.directory?(File.join(File.dirname(__FILE__),'..','..','directory'))
    blah blah blah ...
else
    raise "Can't find directory"
end

I'm trying to find a way to make it fail in the unit tests without doing anything drastic. Being able to overwrite the __ FILE __ variable would be easiest, but as far as I can tell, it's impossible.

Any tips?

Markus Orrelly
  • 1,669
  • 2
  • 12
  • 9

3 Answers3

3

My tip? Refactor!

  • Hahaha, yeah, I thought about that. I was hoping there was some little ruby gem hidden somewhere (no pun intended, and no, not a rubygem) :) – Markus Orrelly Mar 16 '10 at 20:08
  • @Markus Orreley: Glad you're taking it lightly. I do hate it when low-level code is making decisions for itself like this. Unit test provide a great excuse to fix that. –  Mar 16 '10 at 20:28
  • I did figure out how to do it, but I think yours is the real answer. I'll put it down below as another possible answer though – Markus Orrelly Mar 16 '10 at 20:40
1

I didn't mark this as the real answer, since refactoring would be the best way to go about doing it. However, I did get it to work:

wd = Dir.getwd
# moves us up two directories, also assuming Dir.getwd
# returns a path of the form /folder/folder2/folder3/folder4...
Dir.chdir(wd.scan(/\/.*?(?=[\/]|$)/)[0..-3].join)
...run tests...
Dir.chdir(wd)

I had tried to do it using Dir.chdir('../../'), but when I changed back, File.expand_path(File.dirname(__ FILE __)) resolved to something different than what it was originally.

Markus Orrelly
  • 1,669
  • 2
  • 12
  • 9
1

Programming Ruby 1.9 says on page 330 that __FILE__ is read only. It also describes it as a "execution environment variable".

However, you can define __FILE__ within an instance_eval. I don't think that'd help with your problem.

Community
  • 1
  • 1
Andrew Grimm
  • 78,473
  • 57
  • 200
  • 338