どこかにエラーがあると思われるので、カーソルクエリ(例:p collection.find(query).to_a)とコレクション(例:p collection.find.to_a)の結果を確認することをお勧めします。以下は、Ruby 1.9.3、Mongo 2.0.4、mongo-ruby-driver1.6.2で動作します。それがお役に立てば幸いです。おそらく、それが自分にも役立つことを確認し、ソリューションに収束できることを確認できます。
MongoConfig.rb
require "mongo"
KEY = 'my_key'
module MongoConfig
SERVER = 'localhost'
PORT = Mongo::Connection::DEFAULT_PORT
DB = 'my_db'
COLLECTION = 'my_collection'
attr_accessor :db, :collection
def configure
@server = SERVER
@port = PORT
end
def init_collection(connection)
@db = connection[MongoConfig::DB]
@collection = @db[MongoConfig::COLLECTION]
return @collection
end
end
blocking_mongo_fetcher_test.rb
$LOAD_PATH.unshift(File.expand_path("..", __FILE__))
require "test-unit"
require "MongoConfig"
require "BlockingMongoFetcher"
class BlockingMongoFetcherTest < Test::Unit::TestCase
def setup
clear_collection
end
def clear_collection
Mongo::Connection.new[MongoConfig::DB][MongoConfig::COLLECTION].remove
end
def count_various_ways_and_cursor_twice_test
value = 'my name'
query = {KEY => value}
count_command = {'count' => MongoConfig::COLLECTION, 'query' => { KEY => value} }
fetcher = BlockingMongoFetcher.new
assert_equal(0, fetcher.collection.count) # collection count
assert_equal(0, fetcher.collection.find(query).count) # cursor count
assert_equal(0, fetcher.db.command(count_command)['n'].to_i) # db command count
assert_nil(fetcher.fetch(value))
fetcher.collection.insert({KEY => value})
fetcher.collection.insert({KEY => 'x'})
assert_equal(2, fetcher.collection.count) # collection count
assert_equal(1, fetcher.collection.find(query).count) # cursor count
assert_equal(1, fetcher.db.command(count_command)['n'].to_i) # db command count
assert_equal(value, fetcher.fetch(value)[KEY])
cursor = fetcher.collection.find(query)
assert_equal(1, cursor.count) # check once
assert_equal(1, cursor.count) # check twice
end
test "basic test" do
count_various_ways_and_cursor_twice_test
end
test "repeated test" do
100.times do
clear_collection
count_various_ways_and_cursor_twice_test
end
end
end