Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Switch between fake & real fs. #24

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
30 changes: 30 additions & 0 deletions spec/memfs_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,36 @@
end
end

describe '.halt' do
before :each do
described_class.activate!
described_class.deactivate!
end
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What is the purpose of this before block?


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 '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