[rspec-users] [RSpec] Putting shared specs in a separate file

Matt Wynne matt at mattwynne.net
Sat Jan 17 17:57:05 EST 2009


On 17 Jan 2009, at 19:16, LesFreeman wrote:

> Hello,
> I am trying to move shared specs out of my spec_helper and into
> separate files. I found an article about the process here:http://
> blog.kineticweb.com/articles/2008/04/15/automagical-rspec-shared-
> example-loading-from-separate-files
>
> Essentially, I created a spec/shared directory, then a file in that
> dir called controller_authorization_specs.rb
>
> #controller_authorization_specs.rb
> module ControllerAuthorizationSpecs
>  shared_examples_for "test" do
>  end
> end
>
> Then, in my spec helper, some code to load the shared spec files:
> #spec_helper.rb
> ...
> Dir[File.dirname(__FILE__)+'/**/shared/*'].each { |group|
>  require group
>  include Object.const_get(group.match(/.*[\/]{1}([\w]*)
> [.rb]./).captures.first.camelize)
> }
> ...
>
>
> Which seems dandy. But, I get these kind of errors:
> /Users/lesfreeman/Sites/equvents/spec/shared/
> controller_authorization_specs.rb:4: undefined method
> `shared_examples_for' for ControllerAuthorizationSpecs:Module
> (NoMethodError)
> 	from /Library/Ruby/Site/1.8/rubygems/custom_require.rb:31:in
> `gem_original_require'
> 	from /Library/Ruby/Site/1.8/rubygems/custom_require.rb:31:in
> `require'
> 	from /Library/Ruby/Gems/1.8/gems/activesupport-2.2.2/lib/
> active_support/dependencies.rb:155:in `require'
> 	from /Users/lesfreeman/Sites/equvents/spec/spec_helper.rb:11
> 	from /Users/lesfreeman/Sites/equvents/spec/spec_helper.rb:10:in
> `each'
> 	from /Users/lesfreeman/Sites/equvents/spec/spec_helper.rb:10
> 	from /Library/Ruby/Site/1.8/rubygems/custom_require.rb:31:in
> `gem_original_require'
> 	from /Library/Ruby/Site/1.8/rubygems/custom_require.rb:31:in
> `require'
> 	 ... 6 levels...
> 	from ./spec/controllers/../spec_helper.rb:7:in `each'
> 	from ./spec/controllers/../spec_helper.rb:7
> 	from spec/controllers/sessions_controller_spec.rb:1:in `require'
> 	from spec/controllers/sessions_controller_spec.rb:1
>
> I'm sure there's an easy solution, but I'm scratching my head. Any
> help would be greatly appreciated

I suggest you post a comment on the blog post where you got this idea  
from, because it seems incomplete to me - I can't make sense of it.

Some of us who have been using RSpec for a while have found that using  
'macros' to generate examples dynamically is often a better technique  
for re-using specs. You might want to check out this post:

http://www.benmabey.com/2008/06/08/writing-macros-in-rspec/


Matt Wynne
http://blog.mattwynne.net
http://www.songkick.com



More information about the rspec-users mailing list