Counting the number of queries performed

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

    I ended up creating a tiny gem to abstract this problem: sql_spy.

    Just add it to your Gemfile:

    gem "sql_spy"
    

    Wrap your code inside SqlSpy.track { ... }:

    queries = SqlSpy.track do
      # Some code that triggers ActiveRecord queries
      users = User.all
      posts = BlogPost.all
    end
    

    ...and use the return value of the block in your assertions:

    expect(queries.size).to eq(2)
    expect(queries[0].sql).to eq("SELECT * FROM users;")
    expect(queries[0].model_name).to eq("User")
    expect(queries[0].select?).to be_true
    expect(queries[0].duration).to eq(1.5)
    

提交回复
热议问题