[rspec-users] Problems using config.extend(Macro)

David Chelimsky dchelimsky at gmail.com
Tue Jan 10 08:56:34 EST 2012

On Jan 10, 2012, at 7:21 AM, Ants Pants wrote:

> Under Ruby 1.8.7 - Rails 2.3.11 - Rspec 1:
> I have model_macros.rb under spec/spec_helpers and it runs beautifully.
> Dir[File.expand_path(File.join(File.dirname(__FILE__), 'spec_helpers', '**', '*.rb'))].each { require f }
> config.extend(ModelMacros, :type => :model)
> Exactly the same code under Ruby 1.9.2 - Rails 3.1.3 - Rspec 2 gives me ... uninitialized constant ModelMacros (NameError)
> Dir[Rails.root.join("spec/spec_helpers/**/*.rb")].each {|f| require f}
> config.extend(ModelMacros, :type => :model)
> .... which makes sense as it's missing the namespace (but how did it run under 2.3.11. Is Ruby 1.8.7 more lenient? - I doubt it)

That would make sense if Rails was autoloading (implicit) this, but it's not - spec_helper.rb is loading it explicitly. I think the namespace thing is a red herring.

> So I added the namespace and I got rid of that error 
> config.extend(SpecHelpers::ModelMacros, :type => :model)
> But sadly the methods that are called from within the model specs are unable to be found...... Exception encountered: #<NoMethodError: undefined method `it_should_require_attributes'
> This is only solved by including extend SpecHelpers::ModelMacros in the model spec file. Not what I want.

Which suggests that the config is being silently ignored, even though the loading is working.

> Is there something I am missing while migrating all my code? Is there some really basic Ruby thing I have forgotten to do to get this module included?
> I also tried config.include(SpecHelpers::ModelMacros, :type => :model) but to no avail.

That would never have worked under any version because "include" exposes methods to the example scope, not the group scope:

describe "something" do
  # methods in modules added using extend are available here
  it "does something" do
    # methods in modules added using include are available here

> Any help would be great, thank you.

My best guess is that you don't need the namespace, and you should leave Rails out of loading this. Try this:

  Dir["spec_helpers/**/*.rb"].each {|f| require f}
  RSpec.configure do |config|
    config.extend(ModelMacros, :type => :model)

That should work to load the file, since RSpec adds"./spec" to the $LOAD_PATH.

If that doesn't work, it might be that ":type => :model" isn't working correctly, so try "path => /spec\/model/" instead. Please report back and let us know which, if either, works for you.


More information about the rspec-users mailing list