使用 Rake 在 Ruby 中解析的文件路径

File paths for parsing in Ruby using Rake

所以我正在编写一个测试来定位特定文件 metadata.json 以解析为 Ruby 的 JSON gem 以使用 [=29 进行测试=].我的目录层次结构如下所示:

|_tests
   - metadata.json
   - Rakefile
   - Gemfile
   |_specs
     -tagging_specs

该代码是一个简单的文件读取,传入相对路径,因此:

print "Getting values from metadata.json file"
#Path to metadata.json file
metadata = File.read('../metadata.json')
values = JSON.parse(metadata)

使用 rspec 命令直接调用时效果很好。但是当我计划进行多项测试时,我选择使用 Rake 来管理我的规范。但是,由于这样做我得到一个错误并且必须传递完整的目录路径,例如 home/work/projects/tests/metadata.json

我在使用 ../metadata.json 和 Rake 时收到的错误消息是:

Failure/Error: metadata = File.read('../metadata.json')

Errno::ENOENT:
No such file or directory @ rb_sysopen - ../metadata.json
./spec_tests/tagging_standards_spec.rb:7:in 'read'
./spec_tests/tagging_standards_spec.rb:7:in 'block in <top (required)>'
./spec_tests/tagging_standards_spec.rb:3:in '<top (required)>'
No examples found.

Finished in 0.00072 seconds (files took 0.17953 seconds to load)
0 examples, 0 failures, 1 error occurred outside of examples

如果只有我使用这些测试,这不会成为问题。然而,它们旨在为其他人提供工作基础,因此它们的目录路径当然会有所不同。那么在 Ruby 或 Rake 中有没有办法使它更具动态性和可重用性?

__dir_ 方法 returns 您所在的当前文件的目录,所以这应该适合您:

File.read(__dir__ + "/../metadata.json")

此外,要获得 "full path",您可以使用 File::expand_path

Converts a pathname to an absolute pathname. Relative paths are referenced from the current working directory of the process unless dir_string is given, in which case it will be used as the starting point. The given pathname may start with a “~”, which expands to the process owner’s home directory (the environment variable HOME must be set correctly). “~user” expands to the named user’s home directory.

例如:

File.expand_path('../metadata.json',__FILE__)

这里它会首先解析__FILE__的父目录,即当前调用它的文件,例如Rakefile 然后它将使用作为 ../metadata.json 传递的相对路径来查找请求的特定文件并解析绝对路径