分析由 Mongoid 事件生成的 ActiveRecord 对象时,Rspec 测试随机失败 [英] Rspec tests failing randomly when analysing ActiveRecord objects generated by Mongoid events

查看:17
本文介绍了分析由 Mongoid 事件生成的 ActiveRecord 对象时,Rspec 测试随机失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我实现了一种基于 Mongoid 的活动日志记录机制,可以在 MongoDB 中保存事件.

I implemented an activity logging mechanism based on Mongoid that saves events in MongoDB.

Mongoid 模型 Activity 具有 after_create 事件,这些事件根据记录的活动类型执行不同的任务:(简化示例)

The Mongoid model Activity has after_create events that perform different tasks depending on the type of activity logged: (Simplified example)

class Activity
  include Mongoid::Document

  after_create do |activity|
    method_name = "after_#{activity.event_type}"
    send(method_name) if respond_to? method_name
  end

  def after_user_did_something
    MyItem.create!(:type => :user_did_something)
  end
end

测试如下:

 it 'should hide previous [objects] create a new updated one' do
      2.times do 
        user.log_activity(:user_did_something) 
      end
      items = MyItems.where(:type => :user_did_something)
      items.count.should == 2
    end
 end

有时,当 items.count 为 0 而不是 2 时,测试会失败.这仅在从命令行运行时发生 rspec spec仅运行此测试或使用 Guard 运行所有测试时不会发生这种情况.

Sometimes, the tests fails on items.count being 0 instead of 2. This happens only when running from the command line rspec spec it never happens when running only this test, or when running all the tests with Guard.

推荐答案

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

In a typical Mongodb setup, there can be a delay between when a database write returns successfully and when that data can be read. There are two reasons for this:

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

为了确保你总是可以立即读回你刚刚用Mongoid写的数据,你需要设置数据库会话选项consistency::strong,safe:true,这两个选项都不是默认的.

To ensure that you can always immediately read back the data you just wrote using Mongoid, you need to set the database session options consistency: :strong, safe: true, neither of which are the default.

这篇关于分析由 Mongoid 事件生成的 ActiveRecord 对象时,Rspec 测试随机失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆