RSpec can only see classes in the root of my lib directory

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

 no such file to load -- test (LoadError) 

It looks like my specifications can be nested in a folder structure, but the moment I try and require a class that is in a subfolder (e.g. lib/workers/conversion_worker.rb ), I get this error.

I use require 'spec_helper' in all my specifications, but even hard-coded the path in which the classes lead to the same error.

With this structure:

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

The spectrum is as follows:

 # spec/workers/class_not_found_spec.rb require "spec_helper" require "class_not_found" describe ClassNotFound do it "Does something" end 

As a result, the specification starts successfully (the -I flag adds the path to $ LOAD_PATH):

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

So it looks like RSpec is not adding anything below lib to its path.

I can successfully execute class_not_found.rb using require_relative:

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

But do not use require:

 require "lib/workers/class_not_found.rb" # Fails 
+4
source share
2 answers

I do not know if you have any other answer, but it seems that you do not need your files correctly.

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

 require 'workers/class_not_found' 

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

 require 'class_found' 

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

+7
source

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

 require 'workers/class_not_found' 

will be correct.

By the way: you do not require classes, you require files.

0
source

All Articles