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
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)