Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Customizing Rspec generators in Rails 3

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.

like image 924
tomjakubowski Avatar asked Dec 22 '22 07:12

tomjakubowski


2 Answers

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.

like image 188
Martin Harrigan Avatar answered Dec 30 '22 08:12

Martin Harrigan


Copy the '/lib/generators/rspec/scaffold/templates/controller_spec.rb' file from the rspec-rails gem to your 'app/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.

like image 35
Shannon Avatar answered Dec 30 '22 08:12

Shannon