如何使用 Mongoid 驱动程序在 Rails 测试环境中启用 Mongo 索引?

How to enable Mongo indexes in Rails test environment with Mongoid driver?

我有一个像这样的 MongoId 模型:

module Acme
  class Account
    include Mongoid::Document
    include Mongoid::Timestamps

    field :username

    index({'username': 1}, {unique: true})
  end
end

我想编写一些单元测试,但我希望在我的测试套件中创建此类模型时启用此索引。

默认情况下似乎没有启用索引。

有线索吗?

P.S。我正在研究 Rails 4,使用 mongoid gem: 5.1.3.

Acme::Account.create_indexes

将创建索引。所以你可以在你的测试中调用它。例如在 before :eachbefore :suite 块中。