Rspec 2 和 Rails 3 存根/模拟
我目前正在将一个大型应用程序从 Rails 2 迁移到 Rails 3。在我们的功能规范中,我们有很多这样的东西:
@model = Factory :model
@child = Factory :child
Model.stub!(:find).and_return(@model)
Child.stub!(:find).and_return(@child)
...
@child.should_receive(:method).twice
主要问题是,如果我让它访问数据库并获取子级的实际实例,真实的:方法会使测试过于复杂(需要两个大工厂)并且缓慢。
在代码中,我们使用各种方式来获取项目:查找、动态查找器等,
@model = Model.find(1)
@child = @model.children.find_by_name(name)
您如何建议将此逻辑移至 Rails 3?对另一个存根/模拟库有什么建议吗?
I am currently in the process of migration to rails 3 from rails 2 in a large application. In our functional specs, we have alot of stuff like this:
@model = Factory :model
@child = Factory :child
Model.stub!(:find).and_return(@model)
Child.stub!(:find).and_return(@child)
...
@child.should_receive(:method).twice
The main issue is that if I let it hit DB and get actual instance of child, real :method makes tests too complex (need two big factories) and slow.
In code we use various ways to get items: find, dynamic finders, etc
@model = Model.find(1)
@child = @model.children.find_by_name(name)
How would you advice to move this logic to rails 3? Any advice on another stubbing/mocking library maybe?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
通常,您会在控制器规格内模拟模型:
但是,当您的 Rails 3 应用程序的 Gemfile 中有
gem "rspec-rails", "~> 2.0"
时,标准的 Rails 脚手架生成器将使用 rspec 为您生成规范,因此运行railsgeneratescaffold MyResource
将为您生成一些示例规范。以下是rails/rspec 将为控制器规格生成的内容的简单注释版本,因此我认为这应该被视为“RSpec 方式”。
Normally you would mock the model inside controller specs:
However, when you've got
gem "rspec-rails", "~> 2.0"
in your rails 3 app's Gemfile, then the standard rails scaffold generator will use rspec to generate specs for you, so runningrails generate scaffold MyResource
will generate some example specs for you.The following is a lightly annotated version of what rails/rspec will generate for controller specs, so I suppose this should be considered "The RSpec Way".