Search code examples
ruby-on-railsrubyrake

File paths for parsing in Ruby using Rake


So I'm writing a test that locates a particular file metadata.json to be parsed to Ruby's JSON gem to be tested using RSpec. My directory hierarchy looks like this:

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

The code was a simple file read passing in the relative path, so:

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

Which worked fine when invoked directly using the rspec command. But as I plan to right multiple tests I opted to use Rake to manage my specs. Since doing this however I get an error and have to pass in a full directory path such as home/work/projects/tests/metadata.json

The error message I get is when using ../metadata.json with Rake is:

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

This woukdnt be a problem if it was just me using these tests. However they're meant to provide the base for others to do their work, so their directory paths will of course be different. So is there a way in Ruby or Rake to make this more dynamic and reusable?


Solution

  • __dir_ method returns directory of the current file you're in, so this should work for you:

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