Counting the number of queries performed

后端 未结 8 1863
[愿得一人]
[愿得一人] 2020-12-08 01:53

I\'d like to test that a certain piece of code performs as few SQL queries as possible.

ActiveRecord::TestCase seems to have its own assert_querie

8条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-08 02:55

    Here's another formulation of Ryan's and Yuriy's solution that's just a function you add to your test_helper.rb:

    def count_queries &block
      count = 0
    
      counter_f = ->(name, started, finished, unique_id, payload) {
        unless payload[:name].in? %w[ CACHE SCHEMA ]
          count += 1
        end
      }
    
      ActiveSupport::Notifications.subscribed(counter_f, "sql.active_record", &block)
    
      count
    end
    

    Usage is just:

    c = count_queries do
      SomeModel.first
    end
    

提交回复
热议问题