使用 RSpec 测试使用 include 方法的活动记录范围
给定以下两个类:
class Location < ActiveRecord::Base
belongs_to :holiday_schedule
validates :name, :presence => true, :uniqueness => {:case_sensitive => false}
scope :with_holiday_schedule, includes(:holiday_schedule)
end
class HolidaySchedule < ActiveRecord::Base
validates_presence_of :name
has_many :locations
end
如何指定 with_holiday_schedule 范围以确保循环中访问 location.holiday_schedule.name 不会导致 N+1 查询问题?
Given the following two classes:
class Location < ActiveRecord::Base
belongs_to :holiday_schedule
validates :name, :presence => true, :uniqueness => {:case_sensitive => false}
scope :with_holiday_schedule, includes(:holiday_schedule)
end
class HolidaySchedule < ActiveRecord::Base
validates_presence_of :name
has_many :locations
end
How would you spec the with_holiday_schedule scope to ensure that accessing location.holiday_schedule.name in a loop will not cause the N+1 Query problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在提交给 RSpec 用户邮件列表并阅读更多有关规范的一般信息后,我最终意识到这不值得进行单元测试。 :includes 指令在 Rails 中经过了很好的测试,并且测试该简单行的开销高于与其失败或被其他开发人员删除相关的风险 - 至少在我的情况下是这样。
我真正关心的是应用程序的性能。规范性能比跳过障碍对这条线进行单元测试要高效得多。
After positing to the RSpec users mailing list and reading more about speccing in general, I ultimately came to the realization that this isn't worth a unit test. The :includes directive is well tested in rails and the overhead of testing that simple line is higher than the risk associated with it failing or being removed by another developer - at least in my case.
What I really care about is performance of the application. Speccing performance would be a lot more productive than jumping through hoops to unit test this line.
查看计算执行的查询数量。
这应该在您的解决方案中完美运行。
他们已经这样做了:
您可以在规范中以这种方式使用它:
我希望这会起作用。
Have a look at Counting the number of queries performed.
This should work perfectly in your solution.
They've done this:
You can use it this way in your spec:
I hope this will work.