diff --git a/lib/fakefs.rb b/lib/fakefs.rb index 7eb5490..f63a5c1 100644 --- a/lib/fakefs.rb +++ b/lib/fakefs.rb @@ -224,14 +224,15 @@ module FakeFS end def chdir(dir, &blk) - raise "you must pass in a block" unless blk - new_dir = find(dir) - raise Errno::ENOENT unless new_dir - dir_levels.push dir - blk.call + dir_levels.push dir if blk + + raise Errno::ENOENT, dir unless new_dir + + dir_levels.push dir if !blk + blk.call if blk ensure - dir_levels.pop + dir_levels.pop if blk end def path_parts(path) @@ -246,6 +247,10 @@ module FakeFS File.expand_path(File.join(*parts)) end end + + def current_dir + find(normalize_path('.')) + end end class MockFile diff --git a/test/fakefs_test.rb b/test/fakefs_test.rb index 456524b..51b0d8c 100644 --- a/test/fakefs_test.rb +++ b/test/fakefs_test.rb @@ -165,10 +165,6 @@ class FakeFSTest < Test::Unit::TestCase 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_keep_us_from_absolute_paths @@ -226,9 +222,34 @@ class FakeFSTest < Test::Unit::TestCase rescue Exception # hardcore end + Dir.chdir('/path') do + begin + Dir.chdir('nope'){ } + rescue Errno::ENOENT + end + + assert_equal ['/path'], FileSystem.dir_levels + end + assert_equal(['foo', 'foobar'], FileSystem.fs['path'].keys.sort) end + def test_chdir_with_no_block_is_awesome + FileUtils.mkdir_p '/path' + Dir.chdir('/path') + FileUtils.mkdir_p 'subdir' + assert_equal ['subdir'], FileSystem.current_dir.keys + Dir.chdir('subdir') + File.open('foo', 'w'){|f| f.write 'foo'} + assert_equal ['foo'], FileSystem.current_dir.keys + + assert_raises(Errno::ENOENT) do + Dir.chdir('subsubdir') + end + + assert_equal ['foo'], FileSystem.current_dir.keys + end + def test_file_open_defaults_to_read File.open('foo','w'){|f| f.write 'bar' } assert_equal 'bar', File.open('foo'){|f| f.read }