Search code examples
ruby-on-railsactiverecordrspecnamed-scope

Using RSpec to test active record scope that uses the includes method


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?


Solution

  • 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.