From e3446636e50bd96019f787329b297e7a33da96a9 Mon Sep 17 00:00:00 2001 From: Scott Taylor Date: Wed, 30 Sep 2009 03:20:59 -0400 Subject: [PATCH] Create files in w, w+, a, and a+ modes when calling File.new and the file is missing. --- lib/fakefs/file.rb | 13 ++++++++----- test/fakefs_test.rb | 20 ++++++++++++++++++++ 2 files changed, 28 insertions(+), 5 deletions(-) diff --git a/lib/fakefs/file.rb b/lib/fakefs/file.rb index 0d81d0b..ef0a844 100644 --- a/lib/fakefs/file.rb +++ b/lib/fakefs/file.rb @@ -108,7 +108,7 @@ module FakeFS @file = FileSystem.find(path) @open = true - check_file_existence! if !file_creation_mode? + file_creation_mode? ? create_missing_file : check_file_existence! end def close @@ -134,10 +134,7 @@ module FakeFS raise IOError, 'closed stream' unless @open raise IOError, 'not open for writing' if read_only? - if !File.exists?(@path) - @file = FileSystem.add(path, FakeFile.new) - end - + create_missing_file @file.content += content end alias_method :print, :write @@ -170,5 +167,11 @@ module FakeFS raise ArgumentError, "illegal access mode #{mode}" end end + + def create_missing_file + if !File.exists?(@path) + @file = FileSystem.add(path, FakeFile.new) + end + end end end diff --git a/test/fakefs_test.rb b/test/fakefs_test.rb index fd444ef..e270833 100644 --- a/test/fakefs_test.rb +++ b/test/fakefs_test.rb @@ -126,6 +126,26 @@ class FakeFSTest < Test::Unit::TestCase end end + def test_creates_files_in_write_only_mode + File.open("foo", "w") + assert File.exists?("foo") + end + + def test_creates_files_in_read_write_truncate_mode + File.open("foo", "w+") + assert File.exists?("foo") + end + + def test_creates_files_in_append_write_only + File.open("foo", "a") + assert File.exists?("foo") + end + + def test_creates_files_in_append_read_write + File.open("foo", "a+") + assert File.exists?("foo") + end + def test_can_read_files_once_written path = '/path/to/file.txt' File.open(path, 'w') do |f|