假的Ruby文件系统 [英] Fake filesystem for Ruby

查看:187
本文介绍了假的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 - 重写代码以使其更加精确可测试

您本质上是将 / 硬编码为应用程序开始查找文件的根源。如果你是可配置的,你的代码可以操纵这个测试。



例如:

  $ 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 以获得更多信息。



就我个人而言,我会选择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 /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!

解决方案

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.

这篇关于假的Ruby文件系统的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆