Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
991 views
in Technique[技术] by (71.8m points)

ruby on rails - Rspec tests failing randomly when analysing ActiveRecord objects generated by Mongoid events

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

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

The test looks like this:

 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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

  • For performance gains, an "unsafe" write can return before the data is committed to the disk.
  • Mongodb uses replica sets and there is a replication delay. Commonly reads are distributed to the replicas as a form of load balancing, so even if you use a safe write, you may be reading from a different server than the one you just wrote to and thus not see the data you just wrote.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...