Counting the number of queries performed

后端 未结 8 1865
[愿得一人]
[愿得一人] 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:57

    My vision of Ryan's script (cleaned up a bit and wrapped in a matcher), hope it is still actual for someone:

    I put this to spec/support/query_counter.rb

    module ActiveRecord
      class QueryCounter
    
        attr_reader :query_count
    
        def initialize
          @query_count = 0
        end
    
        def to_proc
          lambda(&method(:callback))
        end
    
        def callback(name, start, finish, message_id, values)
          @query_count += 1 unless %w(CACHE SCHEMA).include?(values[:name])
        end
    
      end
    end
    

    and this to spec/support/matchers/exceed_query_limit.rb

    RSpec::Matchers.define :exceed_query_limit do |expected|
    
      match do |block|
        query_count(&block) > expected
      end
    
      failure_message_for_should_not do |actual|
        "Expected to run maximum #{expected} queries, got #{@counter.query_count}"
      end
    
      def query_count(&block)
        @counter = ActiveRecord::QueryCounter.new
        ActiveSupport::Notifications.subscribed(@counter.to_proc, 'sql.active_record', &block)
        @counter.query_count
      end
    
    end
    

    Usage:

    expect { MyModel.do_the_queries }.to_not exceed_query_limit(2)
    

提交回复
热议问题