Koobz
Koobz

Reputation: 6938

Testing rails query counts

I'm trying to write a test to ensure that we're not running more queries than necessary. I found the ActiveRecord testcase and tried to inherit from it. This test case has some useful methods like assert_queries(num). Problem - it doesn't seem to work in 3.2.12 and it's been deprecated.

Is there somewhere I can access the query log? I'm opening up pry shell during one of my test cases in an attempt to inspect some query logging object. No dice.

A bit along these lines - is there any facility for registering callbacks outside of a model? For example, I want to register a block that listens for all object save methods.

Upvotes: 2

Views: 190

Answers (1)

cmrichards
cmrichards

Reputation: 1772

"is there any facility for registering callbacks outside of a model?"

ActiveRecord::Observer should do exactly what you want. This code 'observes' the Comment model :

class CommentObserver < ActiveRecord::Observer
  def after_save(comment)
    Notifications.comment("[email protected]", "New comment was posted", comment).deliver
  end
end

For more examples and advanced usage see http://api.rubyonrails.org/classes/ActiveRecord/Observer.html

Upvotes: 2

Related Questions