1

I have this small project I've been working on. In this project, I've been using the rspec to test the classes, so my project folder is structured like this:

.
+--lib
|   +-- # bunch of classes 
|
+--spec
|   +-- # bunch of tests

Being in the project root, if I run rspec all the tests are ran correctly.

However, if I run the main script through the command line, like this: ruby lib/main.rb, then I get this error:

`require': cannot load such file

If I change all the requires to ./lib/class_name it works, but the rspec stops working.

What is the right way to do this?

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
Rafael Costa
  • 1,291
  • 2
  • 13
  • 30
  • 1
    Right, there's no rails tag. In this case, the generic answer would be "Set up your `$LOAD_PATH` so that all needed directories are there". That's how `require` works. It searches for the thing in each directory in your LOAD_PATH – Sergio Tulentsev Apr 17 '17 at 15:03
  • 1
    Maybe you should use [require_relative](http://stackoverflow.com/questions/3672586/what-is-the-difference-between-require-relative-and-require-in-ruby) – Bohdan Apr 17 '17 at 15:49
  • I think the best solution would be similar to what is done here https://github.com/google/google-api-ruby-client/blob/master/spec/spec_helper.rb They've simply appended the required paths into `$LOAD_PATH` then 'required' this helper in the tests . As far as I know if you are typing in exact paths, `require_relative` loads the exact same paths as `require`. – whodini9 Apr 17 '17 at 18:47
  • Can you give concrete example which doesn't work? I never had a problem with this so I can't imagine how it's not working. Also main script should be in project root folder, not in lib. – Marko Avlijaš Apr 18 '17 at 02:32

1 Answers1

0

So, I took Sergio Tulentsev advise and setted up the $LOAD_PATH and that solved my problem!

To do that I added the following code in the beginning of my main script:

$LOAD_PATH.unshift(File.dirname(__FILE__))

This code adds the current file directory to the beginning of the $LOAD_PATH(which is an array used by the require to mount the required files paths and load them).

In other words, this abled my main script to add lib to the $LOAD_PATH and fix the requires.

Rafael Costa
  • 1,291
  • 2
  • 13
  • 30