在 Rails 3 中自定义 Rspec 生成器
我正在编写一个 Rails 3.1 引擎并使用 RSpec 2 进行测试。当我使用 railsgenerate
时,我会自动为我生成规范文件,这非常方便:
$ 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
但是,为了使生成的规范能够很好地发挥作用使用我的独立命名空间,我每次都必须将规范手动包装在模块中:
require 'spec_helper'
module MyEngine
describe Foo do
it "should be round"
...
end
end
我很想知道是否有一种干净且简单的方法来修改自动生成的规范“模板”,这样我就不必包装规范在每次生成新模型或控制器时,Module MyEngine
。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用 Rake 任务复制 RSpec 的模板,如下所示:
然后您可以修改
#{Rails.root}/lib/templates/rspec/model/model_spec.rb
中的代码以包含模块名称。You can copy RSpec's templates using a Rake task like:
Then you can modify the code in
#{Rails.root}/lib/templates/rspec/model/model_spec.rb
to include the module name.将“/lib/generators/rspec/scaffold/templates/controller_spec.rb”文件从 rspec-rails gem 复制到“./lib/templates/rspec/scaffold”文件夹,然后对其进行自定义。显然,如果您迁移到新版本的 rspec-rails,您将需要确保您的自定义模板没有过时。
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.