relative File Path in RSpec

前端 未结 3 495
忘了有多久
忘了有多久 2021-01-17 17:37

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.

3条回答
  •  北恋
    北恋 (楼主)
    2021-01-17 18:14

    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

提交回复
热议问题