-
Type: Bug
-
Resolution: Done
-
Priority: Minor - P4
-
None
-
Affects Version/s: None
-
Component/s: Query
Mongoid: 4 ( master at 35aea60 )
Having a criteria like this:
posts = Post.all.includes(:person)
The first time the posts are iterated the person is not fetched from the db - but the second time it is.
require 'mongoid' require 'mongoid/support/query_counter' require 'minitest/autorun' # Ensure backward compatibility with Minitest 4 Minitest::Test = MiniTest::Unit::TestCase unless defined?(Minitest::Test) Mongoid.configure.connect_to("mongoid_test") Mongoid.logger = Logger.new($stdout) Moped.logger = Logger.new($stdout) def count_queries(&block) query_counter = Mongoid::QueryCounter.new query_counter.instrument(&block) query_counter.events.size end class Post include Mongoid::Document belongs_to :person end class Person include Mongoid::Document has_many :posts field :name end class BugTest < Minitest::Test def test_query_count p = Person.create!(name: 'arthurnn') 4.times { Post.create!(person: p) } criteria = Post.all.includes(:person) query_counter = count_queries do criteria.each(&:person) end # this is fine assert_equal 2, query_counter query_counter = count_queries do criteria.each(&:person) end # this fails assert_equal 2, query_counter end end
Finished tests in 0.114663s, 8.7212 tests/s, 17.4424 assertions/s. 1) Failure: BugTest#test_query_count [examples/mongoid_test.rb:49]: Expected: 2 Actual: 43 1 tests, 2 assertions, 1 failures, 0 errors, 0 skips