Fake filesystem for Ruby

二次信任 提交于 2019-12-03 20:44:37

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!