20

I am currently in

Dropbox/96_2013/work/ror/dmc/dmStaffing/QA/selenium_server_wyatt/spec/2day/units/

I can go into irb and require a file but it's a really long require...

require '/home/durrantm/Dropbox/96_2013/work/ror/dmc/dmStaffing/QA/selenium_server_wyatt/spec/2day/units/login_as_admin_spec.rb'
=> true

I want to use require_relative, as in

$ cd /home/durrantm/Dropbox/96_2013/work/ror/dmc/dmStaffing/QA/selenium_server_wyatt/spec/2day/
$ pwd
/home/durrantm/Dropbox/96_2013/work/ror/dmc/dmStaffing/QA/selenium_server_wyatt/spec/2day
$ irb
irb(main):001:0> require_relative 'units/login_as_admin_spec.rb' 

but I get:

LoadError: cannot infer basepath
1

4 Answers 4

32

require_relative requires a file relative to the file the call to require_relative is in. Your call to require_relative isn't in any file, it's in the interactive interpreter, therefore it doesn't work.

You can use the long form of require by explicitly passing the full path:

require './units/login_as_admin_spec.rb'

Or you add the current directory to the $LOAD_PATH and just require as usual:

$LOAD_PATH << '.'
require 'units/login_as_admin_spec'
0
6

This is a known bug in ruby:

If you are using Pry, instead of IRB, this can be fixed by installing the pry-require_relative gem.

gem install pry-require_relative
4

This worked:

require File.expand_path("../login_as_admin_spec.rb", __FILE__)
2
  • Which Ruby version are you on?
    – Aaron K
    May 7, 2013 at 15:15
  • 2
    If you run just File.expand_path("../login_as_admin_spec.rb", __FILE__) you should see __FILE__ get's ignored and you get the full path of just like File.expand_path("./login_as_admin_spec.rb")
    – Aaron K
    May 7, 2013 at 15:24
2

require_relative works in the context of the current source file. This is different than the current working directory. I don't believe irb or pry have an understanding of "this current source file" concept; since you're not actually in a file.

In these REPLs, just use a relative path reference require './units/login_as_admin_spec.rb'.

3
  • didn't work, couldn't find file, tried ./units, units, ../units and none worked. May 7, 2013 at 15:10
  • @MichaelDurrant what was the error and the line of code you typed? It does work, I've done it multiple times.
    – Aaron K
    May 7, 2013 at 15:15
  • pry does, see @gawin's comment, above. Feb 19, 2015 at 21:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.