我在 Rails 项目中使用 Mongoid。为了提高大型查询的性能,我使用includes 方法来预先加载关系。
我想知道是否有一种简单的方法来计算代码块执行的实际查询次数,以便我可以检查我是否includes真的按预期减少了数据库访问次数。就像是:
# It will perform a large query to gather data from companies and their relationships
count = Mongoid.count_queries do
Company.to_csv
end
puts count # Number of DB access
Run Code Online (Sandbox Code Playgroud)
我想使用此功能添加 Rspec 测试,以证明我的查询在更改后仍然有效(例如;从新关系添加数据时)。例如,在 python 的 Django 框架中,为此可以使用assertNumQueries方法。