Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`require': cannot load such file - Ruby + Rspec

Tags:

ruby

rspec

Im having a trouble with loading dependences in a ruby app (non-rails).

Its folder tree

project

  -> bin
  -> lib
    -> modules
      -> file1.rb
      -> file2.rb
  -> spec
    -> file2_spec.rb

My file is

require 'file1'

module File2
end

My spec is

require 'spec_helper'
require_relative '../lib/modules/file2'

In the error message it shows

rspec spec/query_util_spec.rb /home/gustavo/.rvm/rubies/ruby-2.2.0/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require': cannot load such file -- file1 (LoadError)

I tried to add "require_relative" to file1 in my spec and still does not work.

I'll be grateful someone give me some directions

like image 638
Gustavo Rego Avatar asked Dec 04 '25 02:12

Gustavo Rego


2 Answers

Change your File2.rb to this:

require './file1'

module File2
end
like image 74
K M Rakibul Islam Avatar answered Dec 06 '25 17:12

K M Rakibul Islam


When you said "I tried to add "require_relative" to file1 in my spec and still does not work" were you talking about file2_spec.rb?

It just looks like you've not got require_relative in File2?

With the following, I get the same as you:

$ find -type f ./lib/modules/file1.rb ./lib/modules/file2.rb ./spec/file2_spec.rb $ cat lib/modules/file1.rb puts "hello world" $ cat lib/modules/file2.rb require 'file1' $ cat spec/file2_spec.rb require_relative '../lib/modules/file2' $ ruby spec/file2_spec.rb /opt/chefdk/embedded/lib/ruby/site_ruby/2.1.0/rubygems/core_ext/kernel_require.rb:54:in `require': cannot load such file -- file1 (LoadError) from /opt/chefdk/embedded/lib/ruby/site_ruby/2.1.0/rubygems/core_ext/kernel_require.rb:54:in `require' from /apps/stackoverflow/lib/modules/file2.rb:1:in `<top (required)>' from spec/file2_spec.rb:1:in `require_relative' from spec/file2_spec.rb:1:in `<main>'

But with a relative include in file2.rb, it works fine:

$ cat spec/file2_spec.rb require_relative '../lib/modules/file2' $ cat lib/modules/file2.rb require_relative 'file1' $ ruby spec/file2_spec.rb hello world

That said, if you're looking to create a library, then it's probably worth setting up your LOAD_PATH properly so you don't have to do this everywhere:

$ cat spec/file2_spec.rb $LOAD_PATH.unshift("{File.dirname(__FILE__)}/../lib/modules") require 'file2' $ cat lib/modules/file2.rb require 'file1' $ ruby spec/file2_spec.rb hello world

(or just setup your environment variables etc)

NB, the use of

require './file1'

does a require relative to the working directory, so it's not equivalent to

require_relative 'file1'

like image 35
boyvinall Avatar answered Dec 06 '25 15:12

boyvinall



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!