Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RSpec locating resource path

Tags:

ruby

rspec

rspec2

I have a little project (non Rails) and I'm using RSpec for testing. In order to load models I'm using:

require_relative "../lib/checkout"

However I'm encountering the problem with loading config files, for instance, the test no longer locates my "items.csv" when the following:

CSV.foreach("items.csv") do |row|

Note that the problem occurs only when spec is run from the spec directory, i.e:

rspec checkout_spec.rb

Running it from the project root is fine:

rspec spec/checkout_spec.rb

Any help would be appreciated.

like image 351
alexs333 Avatar asked May 28 '26 15:05

alexs333


1 Answers

CSV.foreach uses the current directory to find the file. You should probably use File.expand_path to get to an absolute path to items.csv to avoid this problem.

Edited to add an example

Assuming that the file is at root/items.csv, and the ruby file with this code is at root/lib/file.rb, you could write

path = File.expand_path File.join(File.dirname(__FILE__), '..', 'items.csv')
CSV.foreach path do |row|
  # rest of code...
like image 95
Jim Deville Avatar answered May 30 '26 04:05

Jim Deville