Rspec tests failing randomly when analysing ActiveRecord objects generated by Mongoid events
activerecord, mongodb, rspec, ruby-on-rails
Solution
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.
Problem
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.