user1922460
user1922460

Reputation:

How do I specify file location in nested directory structure in a Rails app?

Say you have a Rails 4 app with the following directory structure:

my_app
my_app/spec
my_app/spec/models/foo_spec.rb
my_app/spec/support/utilities.rb
my_app/spec/test_files/bar.txt

I have a function in the my_app/spec/support/utilities.rb file that reads data from my_app/spec/test_files/bar.txt to populate the test database with some records before testing the model.

my_app/spec/support/utilities.rb contains

this_path = File.expand_path(File.dirname(__FILE__))
fname = File.join(this_path, '../test_files/bar.txt')

File.open(fname, 'r').each_line do |line|
  # create entries in Foo from tab delimited data
end

This works for opening my_app/spec/test_files/bar.txt, but I was wondering if there was a better way to specify where the file I want to open is located.

Upvotes: 0

Views: 187

Answers (1)

Chris
Chris

Reputation: 788

regarding reading in files, see this question: "require File.dirname(__FILE__)" -- how to safely undo filesystem dependency?

However, seeing your use case I have a few suggestions that may make things easier.

In the case of populating the test database with records prior to testing the model you can do this much easier using Fixtures rather than raw text data. I would suggest taking a look into Fixtures in Ruby on Rails. Utilizing fixtures (example below from http://guides.rubyonrails.org/testing.html) will let you load specific data prior to running your tests. You can also look into using FactoryGirl and sequences to generate data prior to your tests. I have examples of each below.

# in spec/spec_helper.rb or spec/<model_spec> using FactoryGirl
before(:each) do
  (0..100).each do { |n| create(:user, id: 1 + n) }
end

# in spec/spec_helper.rb
before(:all) do
  fixtures :users
end

# in spec/fixtures/users.yml
david:
  name: David Heinemeier Hansson
  birthday: 1979-10-15
  profession: Systems development

steve:
  name: Steve Ross Kellock
  birthday: 1974-09-27
  profession: guy with keyboard

Upvotes: 1

Related Questions