Search code examples
rubyrspecrequire

How to correctly use require? - ruby


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?


Solution

  • 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.