【问题标题】:Using RSpec to test active record scope that uses the includes method使用 RSpec 测试使用 include 方法的活动记录范围
【发布时间】:2011-07-12 14:57:32
【问题描述】:

给定以下两个类:

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 查询问题?

【问题讨论】:

    标签: ruby-on-rails activerecord rspec named-scope


    【解决方案1】:

    在发布到 RSpec 用户邮件列表并阅读更多关于一般规范的信息后,我最终意识到这不值得进行单元测试。 :includes 指令在 Rails 中经过了很好的测试,并且测试该简单行的开销高于与其失败或被其他开发人员删除相关的风险——至少在我的情况下是这样。

    我真正关心的是应用程序的性能。指定性能比跳槽对这条线进行单元测试要高效得多。

    【讨论】:

      【解决方案2】:

      看看Counting the number of queries performed

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

      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
      

      我希望这会奏效。

      【讨论】:

      • 我现在正在测试这个。把它放在 ActiveRecord 命名空间中并不疯狂,所以我会玩一些。
      • 这在大多数情况下都有效。查询实际上等于 2(一个用于位置,一个用于所有相关的假期时间表)。出于某种原因,它可以在手动运行测试时工作,但是在 Guard/Spork 下运行它们时,计数将是 6。在下面添加我的实际解决方案 - 这有点像警察。
      猜你喜欢
      • 1970-01-01
      • 2011-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多