Automagical RSpec: Shared Example Loading from Separate Files

Posted by Justin Reagor Wed, 16 Apr 2008 01:05:00 GMT

I especially love Ruby because I can quickly customize it to my tastes and likes. With out regard for anyone else’s feeling but my own. With that said, I do try and use this power for good. For the better of my office mates.

Earlier today I was doing some of this…

describe Admin::ModelsController do
  shared_examples_for 'all admin pages' do
    code code code here...
  end

  describe 'when logged in' do
    more specific controller specs here...
  end
end

...and I thought to myself that I would really just love to do this…

describe Admin::ModelsController do
  it_should_behave_like 'all admin pages'

  describe 'when logged in' do
    more specific controller specs here...
  end
end

Loading it from some separated out module underneath the specific MVC spec/ sub directories.

I’ll explain more in a second… but using some code I was working on before, thanks to storing it in Yojimbo, I quickly wrote this into my spec_helper.rb…

Dir[File.dirname(__FILE__)+'/**/shared/*'].each { |group| 
  require group
  include Object.const_get(group.match(/.*[\/]{1}([\w]*)[.rb]./).captures.first.camelize)
}

As you can tell from the code, it will go through all sub-directories of the current one (RAILS_ROOT/spec in this case) and rummage for “shared/” directories. It will then try and load modules, within these files, named after the file’s file name.

Without having to require and include each single file/module throughout your spec files (or the parent spec_helper).

Examples:

spec/controllers/shared/all_admin_pages.rb
module AllAdminPages
  shared_examples_for 'all admin pages' do
    code code code here...
  end
end

Of course this is a smallish hack that I think really cleans out my specs. I generally got the idea from app/views/shared or app/views/layouts/shared directories in Rails. Keeping small shared view partials in separate, nicely organized sub-directories.

Let the flaming commence! j/k ;)