Markus Orrelly
Markus Orrelly

Reputation: 1689

Ruby - Is there a way to overwrite the __FILE__ variable?

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?

Upvotes: 1

Views: 525

Answers (3)

Andrew Grimm
Andrew Grimm

Reputation: 81530

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.

Upvotes: 1

Markus Orrelly
Markus Orrelly

Reputation: 1689

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.

Upvotes: 1

user180326
user180326

Reputation:

My tip? Refactor!

Upvotes: 3

Related Questions