Question

RSpec (2.12.2) is giving me a hard time. If I want to reference a class in one of my specs and that class is not in the root of my /lib directory, it throws an error:

no such file to load -- test (LoadError)

It seems that my specs can be nested in a folder structure, but the moment I try and require a class that is in a nested folder (for example lib/workers/conversion_worker.rb), I get this error.

I am using require 'spec_helper' in all my specs, but even hard-coding the path the classes results in the same error.

With this structure:

-lib/
  - class_found.rb
  - workers/
     - class_not_found.rb

The spec looks like this:

# spec/workers/class_not_found_spec.rb
require "spec_helper"
require "class_not_found"

describe ClassNotFound do    
  it "Does something"
end

The following runs the spec successfully (the -I flag adds a path to the $LOAD_PATH):

$ rspec spec/workers/class_not_found_spec.rb -I /Path/to/project/*

So it seems that RSpec isn't adding anything below lib to its path.

I can successfully require class_not_found.rb using require_relative:

require_relative "../../lib/workers/class_not_found.rb" #Succeeds

But not using require:

require "lib/workers/class_not_found.rb" # Fails
Was it helpful?

Solution

I don't know if you have an answer you like yet, but it seems like you aren't requiring your files correctly.

Your 'lib/class_found.rb' file should require all your library files, so it should look something like:

require 'workers/class_not_found'

and your spec_helper.rb will require the main file in your lib folder, so it should look something like:

require 'class_found'

rspec automatically loads 'spec/spec_helper.rb' when it runs, it also automatically adds the 'lib' folder to its LOAD_PATH, so that your requires in 'lib/class_found.rb' are seen and required properly.

OTHER TIPS

According to your directory tree, the file class_not_found.rb is in a subdirectory workers. You forgot to add the path to your require:

require 'workers/class_not_found'

would be correct.

By the way: you don't require classes, you require files.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top