4

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!

pmerino
  • 5,900
  • 11
  • 57
  • 76
  • I **think** [chroot](http://www.ruby-doc.org/core-1.9.3/Dir.html#method-c-chroot) would achieve this. – Tom van der Woerdt Apr 22 '12 at 19:06
  • Well, I though of it initially but after reading the docs, I think it's not suitable for it. It would be some code that when run, "redirects" all the filesystem calls to the faked path – pmerino Apr 22 '12 at 19:10
  • I think maybe `fakefs` gem is what you're looking for: https://github.com/defunkt/fakefs – NARKOZ Apr 22 '12 at 19:11
  • I also took a look at `fakefs`, but it's designed just for tests, not for actual code (I think) – pmerino Apr 22 '12 at 19:13
  • chroot would be the more secure options, otherwise you can have a look at fuse: http://www.debian-administration.org/articles/619 – hellvinz Apr 23 '12 at 17:24

1 Answers1

3

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.

davetron5000
  • 24,123
  • 11
  • 70
  • 98