How to load spec_helper.rb automatically in RSpec 2

When developing gems in Ruby, I almost always need a file in which I can customize RSpec to my needs, and maybe before you do this, some helper modules will need to be available in all my spec examples.

Rails applications use a file called spec/spec_helper.rb for this. It annoys me that in a typical Rails environment, you need to require this spec_helper.rb file in every file that contains examples for loading it. I used to have a lot of problems with this related to changing boot paths and relative requirements in sample files.

Now for my gems, I would like to ask RSpec to require the spec_helper.rb file before downloading any of the sample files. Regardless of the fact, if I call the rspec executable or the rake spec job, which I can define in my Rakefile.

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

Is there a better way to do this?

+46
ruby rspec rspec2
Feb 21 2018-11-21T00:
source share
2 answers

In RSpec 2, the /spec folder is always automatically on the boot 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 this is the minimum you can leave with.

This means that you do not need such a terrible approach as:

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

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

You can also add the parameter to your .rspec file: --require spec_helper , which will require this file in each spec file, without instructions for the instructions at the top.

+108
Feb 23 '11 at 21:00
source share

The string --require spec_helper automatically added to the .rspec file for RSpec 3.0 when you run rspec --init .

+30
Jun 27 '14 at 19:23
source share



All Articles