spec_helper - ruby import rspec




How to load a spec_helper.rb automatically in RSpec 2 (2)

When developing gems in Ruby, I almost always need a file in which I can configure RSpec to my needs and maybe before doing that, require some helper modules which should be available in all my spec examples.

In Rails applications a file named spec/spec_helper.rb is used for that. One thing that annoys me is that in the typical Rails environment, you have to require this spec_helper.rb file in every file that contains examples for it to be loaded. In the past I had a lot of problems with this related to changing load paths and relative require paths inside the example files.

Now for my gems, I would wish to have a way to just say RSpec to require the spec_helper.rb file before loading any of the examples files. Independent of the fact if I call rspec executable, or the rake spec task which I may define in my Rakefile.

I know I can tell RSpec only the location of my spec_helper.rb is this spec_helper.rb requires all the example files manually, but I would also like to avoid the additional maintenance of that approach.

Is there a nicer way to accomplish this?


In RSpec 2, the /spec folder is always automatically on your load path. This means that all you need is:

require 'spec_helper'

at the top of your spec files. This will always load /spec/spec_helper.rb, and is the minimum you'll be able to get away with.

This means you don't need a horrid approach such as:

require File.join(File.dirname(File.dirname(__FILE__)), 'spec_helper.rb')

(which needs to be updated for different nesting levels).

Also you can add to your .rspec file the option: --require spec_helper, which will require this file in each spec file, without the manual require statement at the top.


The --require spec_helper line is automatically added to the .rspec file for RSpec 3.0 when you do rspec --init.





rspec2