如何使用MongoDB通过Mongoid on Rails编写适当的单元测试(以及相关的集成测试)?

我这样问是因为与使用SQLite3相反,即使在运行测试时,我所做的一切都会持续.所以目前我正在编写创建测试,然后手动删除我所做的一切.但是集成测试越来越烦人,甚至变得复杂.

我所做的示例:

before(:each) do
  @user = User.create!(@attr)
end

after(:each) do
  # MongoDB is not a transactional DB, so added objects (create) during tests can't be rollbacked
  # checking for the existance of a similar object with exact :name and :email (regex make it case insensitive)
  cleanup = User.where(:name => "Example User", :email => /^user@example.com/i)
  cleanup.destroy unless cleanup.nil?
end

知道如何让MongoDB在测试期间不持久吗?(我甚至无法在Sandbox 模式下运行控制台,因为要使用Mongoid,我必须停用活动记录).

推荐答案

没有办法让MongoDB不持久.您只需在每次测试之前或之后删除数据.这里有一些相关文件:

http://www.mongodb.org/display/DOCS/Rails+-+Getting+Started#Rails-GettingStarted-Testing

Mongodb相关问答推荐

GO:如何在MongoDB中区分空字符串和nil

MongoDB聚合$group阶段$top与$first在大型数据集上的效率

Mongo $sort然后$group,顺序能保证吗?

如何使用 MindsDB 和 MQL(对于我的 MongoDB 实例)实施零样本分类?

如何在 mongodb golang 的单个更新调用中使用 $set 和 $inc?

从 mongodb Golang 检索时判断零等效时间.时间

在 MongoDB 中使用 findOneAndUpdate 有条件地更新/更新嵌入式数组

使用 AngularJs 和 MongoDB/Mongoose

更新 mongodb 文档中的特定字段

如何将查询结果(单个文档)存储到变量中?

在mongodb中实现分页

使用 MongoDB 更新数组字段内的特定键/值

嵌套在文档数组中的mongodb展开数组

为多个日期范围聚合 $group

如何从 node.js 以编程方式执行 mongodump 命令?

如何在 MongoDB 的 $match 中使用聚合运算符(例如 $year 或 $dayOfMonth)?

如何使用 MongoDB C# 驱动程序有条件地组合过滤器?

如何使用 Pymongo 在 MongoDB 中 Select 单个字段?

MongoDB Compass 中 JSON 输入意外结束

将 FilterDefinition 转换为可以在 mongo shell 中运行的常规 json mongo 查询