Zach
Zach

Reputation: 895

Troublesoot ruby require

Ruby require only works for me with gems not with code that I have written. I'm not sure what it is that I am doing wrong.

This works

require "test-unit"
require "require "C:\\Users\\zreichert\\workspace\\FalconQA\\PageObjects\\Users\\user.rb"

This doesn't work

require "Users/user"
require "Users\user"
require "Users/user.rb"
require "Users\user.rb"
require_relative "Users/user"
require_relative "Users\user"
require_relative "Users/user.rb"
require_relative "Users\user.rb"

The script that I am running is located in - C:/Users/zreichert/workspace/FalconQA/testCases

I have tried to change directories before require like this

Dir.chdir "C:/Users/zreichert/workspace/FalconQA/testCases"

All errors look something like this

c:/Ruby193/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in require': cannot load such file -- Users/user (LoadError) from c:/Ruby193/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:inrequire' from C:/Users/zreichert/workspace/FalconQA/testCases/FAL001.rb:14:in `

Upvotes: 1

Views: 145

Answers (4)

the Tin Man
the Tin Man

Reputation: 160611

As a mental-safety tip, anything looking like "Users\user" will fail because of how escaped characters are interpreted in double-quoted strings.

Instead, use single-quotes for your require parameter to preserve your sanity:

require 'foo'

or

require './relative/path/to/foo'
require '../relative/path/to/bar'

Upvotes: 0

user904990
user904990

Reputation:

you can try

require "./Users/user"

Upvotes: 2

mikej
mikej

Reputation: 66333

Just to expand on Roozbeh's answer slightly, require_relative allows you to load files relative to the location of the file containing the require_relative so doing a chdir will not have any effect on this.

From what you've said in the question, the relative path from FAL001.rb to user.rb is

../PageObjects/Users/user.rb

i.e. up one level and then down into PageObjects/Users, hence

require_relative '../PageObjects/Users/user.rb'

Upvotes: 1

Roozbeh Zabihollahi
Roozbeh Zabihollahi

Reputation: 7347

You can use this:

require_relative '../PageObjects/Users/user.rb'

Slash is better than two backslashes, because it works in both Windows and Linux/MacOS.

Upvotes: 1

Related Questions