Gustavo Rego
Gustavo Rego

Reputation: 335

`require': cannot load such file - 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

Upvotes: 3

Views: 3865

Answers (3)

Gustavo Rego
Gustavo Rego

Reputation: 335

Looking how rspec do this reference stuff in rails, I solved it by add

require File.expand_path("path", __FILE__)

instead of using require_relative

Upvotes: 1

boyvinall
boyvinall

Reputation: 1907

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'

Upvotes: 2

K M Rakibul Islam
K M Rakibul Islam

Reputation: 34336

Change your File2.rb to this:

require './file1'

module File2
end

Upvotes: 4

Related Questions