Configuring Rspec Generators in Rails 3

I am writing a Rails 3.1 engine and testing with RSpec 2. When I use rails generate , I automatically get the specification files for me, 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, in order for the generated specs to play well with my isolated namespace, I have to manually wrap the spec every time in the module:

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

I would really like to know if there is a simple and easy way to modify automatically generated specification templates, so I don’t need to wrap the specification in Module MyEngine every time I create a new model or controller.

+4
source share
2 answers

You can copy RSpec templates using the Rake task, for example:

 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 

You can then change the code in #{Rails.root}/lib/templates/rspec/model/model_spec.rb to include the module name.

+6
source

Copy the file '/lib/generators/rspec/scaffold/templates/controller_spec.rb' from rspec-rails gem to the folder 'app / lib / templates / rspec / scaffold' and then configure it. Obviously, if you upgrade to the new version of rspec-rails, you will want to make sure that your custom template is not out of date.

+4
source

Source: https://habr.com/ru/post/1379248/


All Articles