假的Ruby文件系统 [英] Fake filesystem for Ruby
问题描述
我需要一些伪造实际文件系统的代码。所以,当我启动它时,它将 / home / user / Documents / fake_fs
转换为 /
,所以每个 Dir
或 File
调用进入该目录。例如:
我想在 / some_file
上创建一个文件,所以我使用:
File.open('/ some_file','w')do | f |
f.puts'这个文件上的东西'
end
把它写在 / home / user / Documents / fake_fs / some_file
而不是 / some_file
。有没有办法做到这一点?谢谢!
您有两个选择:
使用Gem将其伪造
FakeFS 一个>会做你想要的东西,但有些文件系统操作不起作用。 FakeFS重写了Ruby标准库中的各种文件操作调用,所以可能会丢失一些东西,或者某些东西可能不正确。选项2 - 重写代码以使其更加精确可测试 您本质上是将 例如: 然后您的测试可以设置 参见 就我个人而言,我会选择2。 I'm in need of some code which fakes the actual file system to a fake one. So, when I start it it converts I want to make a file on And it would write it on You've got two options: 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. You are essentially hardcoding For example: Your tests can then set See Personally, I'd go with option 2. 这篇关于假的Ruby文件系统的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
$ root = ENV ['ROOT_DIR'] || '/'
File.open(File.join($ root,'some_file'),'w')do | file |
#any
end
ROOT_DIR
成为您设置的位置。
$ b chroot
也可能有助于这样做,例如
Dir.chroot(ENV ['ROOT_DIR'] ||'/')
File.open('/ some_file','w')do | file |
#
$ b man chroot
以获得更多信息。
/home/user/Documents/fake_fs
to /
, so every Dir
or File
call goes to that directory. An example:/some_file
, so I use:File.open('/some_file', 'w') do |f|
f.puts 'something on this file'
end
/home/user/Documents/fake_fs/some_file
instead of /some_file
. Is there any way of doing this? Thanks! Option 1 - Use a Gem to Fake it out
Option 2 - Rework your code to make it more testable
/
as the root of where your app starts looking for files. If you make this configurable, your code can manipulate this for tests.$root = ENV['ROOT_DIR'] || '/'
File.open(File.join($root,'some_file'),'w') do |file|
# whatever
end
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
man chroot
for more on that.