Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Relative File Path in RSpec

Tags:

ruby

rspec

I have a RSpec test for a class in /lib/classes which needs access to a zip file (no upload). The file is stored in /spec/fixtures/files/test.zip. How do I input the correct path so its environment agnostic, i.e. without absolute path?

like image 654
wintersolutions Avatar asked Feb 19 '12 00:02

wintersolutions


3 Answers

I've tackled this issue recently and here's what I came up with:

Define a constant in your spec_helper.rb (or equivalent) pointing to RSpec root:

RSPEC_ROOT = File.dirname __FILE__

Use this variable in your *_spec.rb (or equivalent) test files:

require 'spec_helper'

File.open("#{RSPEC_ROOT}/resources/example_data.json")

Why this solution?

  • It doesn't make use of the location of the test file which may be subject to change (spec_helper is likely not)
  • It doesn't require any additions to test files other than the already existing require 'spec_helper'
  • It doesn't depend on Rails (unlike Rails.root)

Here's a Gist: https://gist.github.com/thisismydesign/9dc142f89b82a07e413a45a5d2983b07

like image 174
thisismydesign Avatar answered Nov 15 '22 21:11

thisismydesign


As far as I know (from looking every month or two) there is no better way that building something in spec_helper that uses the __FILE__ value to grab the path to a know bit of content, then build your own helpers on top of that.

You can obviously use a path relative to __FILE__ in the individual *_spec.rb file as well.

like image 21
Daniel Pittman Avatar answered Nov 15 '22 20:11

Daniel Pittman


Rails.root will give you the app root, so

Rails.root.join "spec/fixtures/files/test.zip"

will give you the absolute path of your file, agnostic of the location of the app on your hard drive.

like image 38
Evan Drewry Avatar answered Nov 15 '22 22:11

Evan Drewry