开发者

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?


My tip? Refactor!


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜