diff --git a/lib/fakefs/file.rb b/lib/fakefs/file.rb index fdc8199..72704c9 100644 --- a/lib/fakefs/file.rb +++ b/lib/fakefs/file.rb @@ -109,6 +109,7 @@ module FakeFS @open = true file_creation_mode? ? create_missing_file : check_file_existence! + truncate_file if truncation_mode? end def close @@ -177,5 +178,13 @@ module FakeFS def write_only? @mode == WRITE_ONLY || @mode == APPEND_WRITE_ONLY end + + def truncate_file + @file.content = "" + end + + def truncation_mode? + @mode == READ_WRITE_TRUNCATE || @mode == WRITE_ONLY + end end end diff --git a/test/fakefs_test.rb b/test/fakefs_test.rb index 1d2914c..9eaaf81 100644 --- a/test/fakefs_test.rb +++ b/test/fakefs_test.rb @@ -156,6 +156,22 @@ class FakeFSTest < Test::Unit::TestCase end end + def test_file_in_write_mode_truncates_existing_file + File.open("foo", "w") { |f| f << "contents" } + + f = File.open("foo", "w") + + assert_equal "", File.read("foo") + end + + def test_file_in_read_write_truncation_mode_truncates_file + File.open("foo", "w") { |f| f << "foo" } + + f = File.open("foo", "w+") + + assert_equal "", File.read("foo") + end + def test_file_in_append_write_only_raises_error_when_reading FileUtils.touch("foo")