Dir.chdir support (but not without a block :()

This commit is contained in:
Jeff Hodges 2009-05-30 11:30:46 -07:00
parent af2eb63dbe
commit d9a44e5482
2 changed files with 56 additions and 0 deletions

View File

@ -143,6 +143,10 @@ module FakeFS
def self.[](pattern) def self.[](pattern)
glob(pattern) glob(pattern)
end end
def self.chdir(dir, &blk)
FileSystem.chdir(dir, &blk)
end
end end
module FileSystem module FileSystem
@ -214,6 +218,15 @@ module FakeFS
end end
end end
def chdir(dir, &blk)
raise "you must pass in a block" unless blk
@old_fs = @fs
@fs = find(dir)
blk.call
ensure
@fs = @old_fs
end
def path_parts(path) def path_parts(path)
path.split(File::PATH_SEPARATOR).reject { |part| part.empty? } path.split(File::PATH_SEPARATOR).reject { |part| part.empty? }
end end

View File

@ -145,4 +145,47 @@ class FakeFSTest < Test::Unit::TestCase
# Unsupported so far. More hackery than I want to work on right now # Unsupported so far. More hackery than I want to work on right now
# assert_equal ['/path'], Dir['/path*'] # assert_equal ['/path'], Dir['/path*']
end end
def test_chdir_changes_directories_like_a_boss
# I know memes!
FileUtils.mkdir_p '/path'
assert_equal '.', FileSystem.fs.name
assert_equal({}, FileSystem.fs['path'])
Dir.chdir '/path' do
File.open('foo', 'w'){|f| f.write 'foo'}
File.open('foobar', 'w'){|f| f.write 'foo'}
end
assert_equal '.', FileSystem.fs.name
assert_equal(['foo', 'foobar'], FileSystem.fs['path'].keys.sort)
c = nil
Dir.chdir '/path' do
c = File.open('foo', 'r'){|f| f.read }
end
assert_equal 'foo', c
assert_raise(RuntimeError, 'no block chdir is not yet supported') do
Dir.chdir('/path')
end
end
def test_chdir_shouldnt_lose_state_because_of_errors
FileUtils.mkdir_p '/path'
Dir.chdir '/path' do
File.open('foo', 'w'){|f| f.write 'foo'}
File.open('foobar', 'w'){|f| f.write 'foo'}
end
begin
Dir.chdir('/path') do
raise Exception
end
rescue Exception # hardcore
end
assert_equal(['foo', 'foobar'], FileSystem.fs['path'].keys.sort)
end
end end