Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

require lib in RSpec with Ruby 1.9.2 brings "no such file to load"

I am trying to upgrade one of my Rails projects to Ruby 1.9.2. All went pretty well, but one RSpec test broke. In this test I require a Ruby lib:

# file spec/models/my_lib_spec.rb
require 'spec_helper'
require 'lib/services/my_lib'

describe "MyLib" do

  it "should do something" do
...

The lib looks like this:

# file lib/services/my_lib.rb
class MyLib

  def self.do_something
  ...

In Ruby 1.8.7 (REE) the test worked well:

$ ruby -v   
ruby 1.8.7 (2011-02-18 patchlevel 334) [i686-darwin11.1.0], MBARI 0x6770, Ruby
Enterprise Edition 2011.03
$ rspec ./spec/models/my_lib_spec.rb
..

Finished in 1.4 seconds
2 examples, 0 failures

In Ruby 1.9.2 I get an Error no such file to load:

$ ruby -v
ruby 1.9.2p290 (2011-07-09 revision 32553) [x86_64-darwin11.1.0]
$ rspec ./spec/models/my_lib_spec.rb
/Users/tmangner/.rvm/gems/ruby-1.9.2-p290@madgoal/gems/activesupport-
3.2.2/lib/active_support/dependencies.rb:251:in `require': no such file
to load -- lib/services/my_lib (LoadError)

I have no clue, what keeps Ruby 1.9 from finding the lib.

like image 715
DiegoFrings Avatar asked Jul 07 '12 16:07

DiegoFrings


4 Answers

The load path in ruby 1.9 doesn't work exactly like it did in 1.8.

You need to add the project's root directory to your load path.

You can do this by either running rspec like this:

rspec -I . ./spec/models/tipp_remember_spec.rb

...or by manually adding stuff to the load path in your spec_helper.rb (put this at the top of your spec_helper.rb

$:<< File.join(File.dirname(__FILE__), '..')

I think rspec by default adds your local lib directory to the load path as well, so you might be able to rewrite the require line as follows instead:

require 'services/my_lib'
like image 89
Frost Avatar answered Oct 18 '22 23:10

Frost


In RSpec 2.x, the lib directory is automatically added to the load path (see RSpec-Core#get_started).

So you can just use require 'services/my_lib' in your spec file.

like image 35
Aaron K Avatar answered Oct 18 '22 21:10

Aaron K


If your spec is located spec/models/my_lib_spec.rb and you want to test lib/services/my_lib.rb, then just tell the spec how to get to the lib file

require 'spec_helper'
require_relative '../../lib/services/my_lib'

describe "MyLib" do

  it "should do something" do

Final note: since you're including spec_helper, you typically don't have to give all paths to dependencies, since Rails should load all of these for you.

like image 4
Jesse Wolgamott Avatar answered Oct 18 '22 22:10

Jesse Wolgamott


Try defining the path manually

$LOAD_PATH << './lib/services/'

and then add the library like this

require 'my_lib.rb'
like image 1
Ashton H. Avatar answered Oct 18 '22 22:10

Ashton H.