开发者

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

开发者 https://www.devze.com 2023-03-19 12:16 出处:网络
Given the following two classes: class Location < ActiveRecord::Base belongs_to :holiday_schedule validates :name, :presence => true, :uniqueness => {:case_sensitive => false}

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 < ActiveReco开发者_JS百科rd::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?


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:

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消