Mongoid块直到创建?

时间:2014-03-08 01:00:40

标签: rspec mongoid

我正在使用MongoidFactoryGirl为rspec创建API测试。 Mongoid在生产中不是问题,但在测试API规范时是这样的:

it "renders [person]" do
  person = FactoryGirl.create(:person)
  get 'persons'
  json.count.should eq(1)
end

正在创建的模型实例(在本例中为Person)有时在API调用运行时不会反映在数据库中,从而导致如下错误:

 Failure/Error: json.count.should eq(1)

   expected: 1
        got: 0

   (compared using ==)

如何知道该条目会反映在数据库中,我该如何创建新的数据库条目并阻止进一步执行规范?

4 个答案:

答案 0 :(得分:3)

answer中所述:

  

确保您可以随时立即回读数据   使用Mongoid编写,您需要设置数据库会话选项

consistency: :strong, safe: true
     

这两者都不是默认值。

答案 1 :(得分:1)

你可以使用Fabrications代替工厂女孩...这样更好/更稳定/可以做各种模型......例如我有this problem ......

这是另一个例子

如果您计划制作具有某些条件的模型(订阅用户只能创建评论),以下制作可以做到这一点

Fabricator(:review) do
  rating         { (1..5).to_a.sample }
  content        { Faker::Lorem.sentence(2) }
  subscription   { Fabricate(:subscription) } # review this subscription
  author         { Fabricate(:user) } # author of the review
  before_create do |review|
    # this insures that the author had already subscribed to the subscription
    # so that the review model doesn't throw validation errors.
    subscription.subscribers.create!(user: author)
  end
end

这是FactoryGirl无法做到的事情......

底线我已经使用FactoryGirl 2个月了,我在嵌入式文档方面遇到了很多问题......我已经转移到Fabrications但没有它存在超过4个月的问题......实际上它对集成测试有很大的帮助。

答案 2 :(得分:1)

正如我解释here,使用Mongodb的Mongoid默认为"最终的一致性"因为它提供了更高的性能。

在典型的Mongodb设置中,数据库写入成功返回与可以读取数据之间可能存在延迟。这有两个原因:

  • 为了提高性能,"不安全" write可以在数据提交到磁盘之前返回。
  • Mongodb使用副本集,并且存在复制延迟。通常读取作为负载平衡的形式分发到副本,因此即使您使用安全写入,您可能正在从您刚写入的服务器读取不同的服务器,因此看不到您刚刚写入的数据。

为了确保您可以随时立即回读使用Mongoid编写的数据,您需要设置数据库会话选项consistency: :strong, safe: true,这两个选项都不是默认值。

答案 3 :(得分:0)

你的mongoid.yml中的

更改了测试env的配置,如下所示:

test:
  sessions:
    default:
      hosts:
        - localhost
      database: project-test
  options:
      ...
      consistency: :strong
      safe: true
      ...

这样mongoid会等到mongodb完成操作。