To avoid the n+1 problem, you need to use eager loading in ActiveRecord object associations. An easy implementation of eager loading can be done using named scope in the following way.
class User < ActiveRecord::BaseTo unit test the named scope, you can use this following helper method (keep it in test_helper.rb, if you like) that I wrote for ScrumPad
has_many :friends
named_scope :eager_load_friends, :include => :fiends
end
User.find(user_id).eager_load_friends
def test_eager_loaded(model, association)You can then test your eager loading in the following way
assert !model.instance_variable_get("@#{association.to_s}").nil?
end
def test_eager_load_friendsYou can also use the shoulda plug-in if you like. For me, I think we should test the values returned by our named scope as opposed to shoulda approach, which tests if the code is written as expected.
test_eager_loaded(User.find(1), :friends)
end
Got another solution? I will appreciate if you share.