剔除ActiveRecord::Base.connection
應該訣竅。
需要注意的一件事是在完成所有準備工作(Arrange
部分測試)後完成。例如before(:each)
可能在運行測試之前清理數據庫=> ActiveRecord.connection被觸發,您可能正在創建一些記錄,這些記錄將被ElasticSearch索引=> ActiveRecord.connection被調用。
所以是這樣的:
class WorksSearchSerializer
attr_reader :collection
def initialize(collection)
@collection
end
def as_json
[
{
id: work.id
comment_ids: work.comments.map(&:id)
# ... other stuff that may trigger ActiveRecord call
}
]
end
end
require 'rails_helper'
RSpec.describe WorksSearchSerializer do
ShouldNotDoAnyDBConnection = Class.new(StandardError)
subject { described_class.new(es_works) }
let!(:work) { Work.create! } #this triggers ActiveRecord::Base.connection call
let(:es_works) { Work.__elasticsearch__.search({query: { match_all: {} }}.to_json) }
let(:result) { subject.as_json }
before do
sleep 0.2 # wait for ES reindex
end
it 'should not pull any relational DB records' do
allow(ActiveRecord::Base)
.to receive(:connection)
.and_raise(ShouldNotDoAnyDBConnection)
expect(result).to be_kind_of Array
allow(ActiveRecord::Base)
.to receive(:connection)
.and_call_original
end
end