Fake filesystem for Ruby

2019-03-31 18:09发布

问题:

I'm in need of some code which fakes the actual file system to a fake one. So, when I start it it converts /home/user/Documents/fake_fs to /, so every Dir or File call goes to that directory. An example:

I want to make a file on /some_file, so I use:

File.open('/some_file', 'w') do |f|
  f.puts 'something on this file'
end

And it would write it on /home/user/Documents/fake_fs/some_file instead of /some_file. Is there any way of doing this? Thanks!

回答1:

You've got two options:

Option 1 - Use a Gem to Fake it out

FakeFS will do exactly what you want, with the caveat that some file system operations won't work. FakeFS rewrites various file-manipulating calls in Ruby standard lib, so something might be missed, or something might not work right.

Option 2 - Rework your code to make it more testable

You are essentially hardcoding / as the root of where your app starts looking for files. If you make this configurable, your code can manipulate this for tests.

For example:

$root = ENV['ROOT_DIR'] || '/'
File.open(File.join($root,'some_file'),'w') do |file|
  # whatever
end

Your tests can then set ROOT_DIR to be a location you set up just like you want.

chroot might also help in doing this, e.g.

Dir.chroot(ENV['ROOT_DIR'] || '/')

File.open('/some_file','w') do |file|
  # whatever
end

See man chroot for more on that.

Personally, I'd go with option 2.