views:

43

answers:

2

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?

A: 

My tip? Refactor!

jdv
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
@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.
jdv
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
A: 

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