4

I'm writing a Rails 3.1 engine and testing with RSpec 2. When I use rails generate, I get spec files generated for me automatically, which is so convenient:

$ rails g model Foo
  invoke  active_record
  create    db/migrate/20111102042931_create_myengine_foos.rb
  create    app/models/myengine/foo.rb
  invoke    rspec
  create      spec/models/myengine/foo_spec.rb

However, to make the generated specs play nicely with my isolated namespace, I have to wrap the spec each time manually in a module:

require 'spec_helper'

module MyEngine
  describe Foo do
    it "should be round"
    ...
  end
end

I would love to know if there's a clean and easy way to modify the automatically generated spec 'templates' so that I don't have to wrap the spec in Module MyEngine each time I generate a new model or controller.

2 Answers 2

7

You can copy RSpec's templates using a Rake task like:

namespace :spec do
  namespace :templates do
    # desc "Copy all the templates from rspec to the application directory for customization. Already existing local copies will be overwritten"
    task :copy do
      generators_lib = File.join(Gem.loaded_specs["rspec-rails"].full_gem_path, "lib/generators")
      project_templates = "#{Rails.root}/lib/templates"

      default_templates = { "rspec" => %w{controller helper integration mailer model observer scaffold view} }

      default_templates.each do |type, names|
        local_template_type_dir = File.join(project_templates, type)
        FileUtils.mkdir_p local_template_type_dir

        names.each do |name|
          dst_name = File.join(local_template_type_dir, name)
          src_name = File.join(generators_lib, type, name, "templates")
          FileUtils.cp_r src_name, dst_name
        end
      end
    end
  end
end

Then you can modify the code in #{Rails.root}/lib/templates/rspec/model/model_spec.rb to include the module name.

Sign up to request clarification or add additional context in comments.

Comments

4

Copy the '/lib/generators/rspec/scaffold/templates/controller_spec.rb' file from the rspec-rails gem to your './lib/templates/rspec/scaffold' folder, then customize it. Obviously, if you move to a new version of rspec-rails you will want to make sure that your customized template hasn't gotten stale.

1 Comment

This still works as of rails 7.1 / rspec 3 (but note it needs to be in your app's lib directory (not app/lib))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.