Skip to content

Commit

Permalink
Adding MemFs.halt to swith back to the real file-system for a while (#24
Browse files Browse the repository at this point in the history
)

* Switch between fake & real fs
* Rewritten .halt & implemented .halt spec
* Rewritten MemFs.halt to operate on the newly introduced 'clear' parameter for MemFs.activate!
* New test case: Make sure halt switches back even when an exception occurs
* Removing trailing spaces

Closes #24.
  • Loading branch information
Robin Niemeyer authored and simonc committed Aug 29, 2016
1 parent ac1163c commit 722acb4
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 2 deletions.
24 changes: 22 additions & 2 deletions lib/memfs.rb
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ def activate
#
# @see #deactivate!
# @return nothing.
def activate!
def activate!(clear: true)
Object.class_eval do
remove_const :Dir
remove_const :File
Expand All @@ -79,7 +79,7 @@ def activate!
const_set :File, MemFs::File
end

MemFs::FileSystem.instance.clear!
MemFs::FileSystem.instance.clear! if clear
end
module_function :activate!

Expand All @@ -100,6 +100,26 @@ def deactivate!
end
module_function :deactivate!

# Switches back to the original file system, calls the given block (if any),
# and switches back afterwards.
#
# If a block is given, all file & dir operations (like reading dir contents or
# requiring files) will operate on the original fs.
#
# @example
# MemFs.halt do
# puts Dir.getwd
# end
# @return nothing
def halt
deactivate!

yield if block_given?
ensure
activate!(clear: false)
end
module_function :halt

# Creates a file and all its parent directories.
#
# @param path: The path of the file to create.
Expand Down
37 changes: 37 additions & 0 deletions spec/memfs_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,43 @@
end
end

describe '.halt' do
before(:each) { described_class.activate! }
after(:each) { described_class.deactivate! }

it 'switches back to the original Ruby Dir & File classes' do
described_class.halt do
expect(::Dir).to be(described_class::OriginalDir)
expect(::File).to be(described_class::OriginalFile)
end
end

it 'switches back to the faked Dir & File classes' do
described_class.halt
expect(::Dir).to be(described_class::Dir)
expect(::File).to be(described_class::File)
end

it 'switches back to the faked Dir & File classes no matter what' do
begin
described_class.halt { raise StandardError.new }
rescue
expect(::Dir).to be(described_class::Dir)
expect(::File).to be(described_class::File)
end
end

it 'maintains the state of the faked fs' do
_fs.touch('file.rb')

described_class.halt do
expect(File.exist?('file.rb')).to be false
end

expect(File.exist?('file.rb')).to be true
end
end

describe '.touch' do
around(:each) { |example| described_class.activate { example.run } }

Expand Down

0 comments on commit 722acb4

Please sign in to comment.