使用 RSpec 测试使用 include 方法的活动记录范围

发布于 2024-11-19 13:29:59 字数 459 浏览 1 评论 0原文

给定以下两个类:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

纸伞微斜 2024-11-26 13:29:59

在提交给 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.

情丝乱 2024-11-26 13:29:59

查看计算执行的查询数量

这应该在您的解决方案中完美运行。
他们已经这样做了:

ActiveRecord::Base.count_queries do
  Ticket.first
end

您可以在规范中以这种方式使用它:

queries = ActiveRecord::Base.count_queries do
  location.with_holiday_schedule.holiday_schedule.name
end
queries.should_be == 1

我希望这会起作用。

Have a look at Counting the number of queries performed.

This should work perfectly in your solution.
They've done this:

ActiveRecord::Base.count_queries do
  Ticket.first
end

You can use it this way in your spec:

queries = ActiveRecord::Base.count_queries do
  location.with_holiday_schedule.holiday_schedule.name
end
queries.should_be == 1

I hope this will work.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文