2019-03-30 07:23:56 +00:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2017-07-07 12:49:05 +00:00
|
|
|
require 'spec_helper'
|
|
|
|
|
2020-06-24 18:09:03 +00:00
|
|
|
RSpec.describe EachBatch do
|
2017-07-07 12:49:05 +00:00
|
|
|
describe '.each_batch' do
|
|
|
|
let(:model) do
|
|
|
|
Class.new(ActiveRecord::Base) do
|
|
|
|
include EachBatch
|
|
|
|
|
|
|
|
self.table_name = 'users'
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
before do
|
2020-01-09 18:07:52 +00:00
|
|
|
create_list(:user, 5, updated_at: 1.day.ago)
|
2017-07-07 12:49:05 +00:00
|
|
|
end
|
|
|
|
|
2018-11-04 13:59:13 +00:00
|
|
|
shared_examples 'each_batch handling' do |kwargs|
|
|
|
|
it 'yields an ActiveRecord::Relation when a block is given' do
|
2020-10-08 18:08:32 +00:00
|
|
|
model.each_batch(**kwargs) do |relation|
|
2018-11-04 13:59:13 +00:00
|
|
|
expect(relation).to be_a_kind_of(ActiveRecord::Relation)
|
|
|
|
end
|
2017-07-07 12:49:05 +00:00
|
|
|
end
|
|
|
|
|
2018-11-04 13:59:13 +00:00
|
|
|
it 'yields a batch index as the second argument' do
|
2020-10-08 18:08:32 +00:00
|
|
|
model.each_batch(**kwargs) do |_, index|
|
2018-11-04 13:59:13 +00:00
|
|
|
expect(index).to eq(1)
|
|
|
|
end
|
2017-07-07 12:49:05 +00:00
|
|
|
end
|
|
|
|
|
2018-11-04 13:59:13 +00:00
|
|
|
it 'accepts a custom batch size' do
|
|
|
|
amount = 0
|
2017-07-07 12:49:05 +00:00
|
|
|
|
2020-10-08 18:08:32 +00:00
|
|
|
model.each_batch(**kwargs.merge({ of: 1 })) { amount += 1 }
|
2017-07-07 12:49:05 +00:00
|
|
|
|
2018-11-04 13:59:13 +00:00
|
|
|
expect(amount).to eq(5)
|
|
|
|
end
|
2017-07-07 12:49:05 +00:00
|
|
|
|
2018-11-04 13:59:13 +00:00
|
|
|
it 'does not include ORDER BYs in the yielded relations' do
|
|
|
|
model.each_batch do |relation|
|
|
|
|
expect(relation.to_sql).not_to include('ORDER BY')
|
|
|
|
end
|
2017-07-07 12:49:05 +00:00
|
|
|
end
|
|
|
|
|
2018-11-04 13:59:13 +00:00
|
|
|
it 'allows updating of the yielded relations' do
|
2020-05-22 09:08:09 +00:00
|
|
|
time = Time.current
|
2017-07-07 12:49:05 +00:00
|
|
|
|
2018-11-04 13:59:13 +00:00
|
|
|
model.each_batch do |relation|
|
|
|
|
relation.update_all(updated_at: time)
|
|
|
|
end
|
2017-07-07 12:49:05 +00:00
|
|
|
|
2018-11-04 13:59:13 +00:00
|
|
|
expect(model.where(updated_at: time).count).to eq(5)
|
|
|
|
end
|
2017-07-07 12:49:05 +00:00
|
|
|
end
|
2018-11-04 13:59:13 +00:00
|
|
|
|
|
|
|
it_behaves_like 'each_batch handling', {}
|
|
|
|
it_behaves_like 'each_batch handling', { order_hint: :updated_at }
|
2020-12-22 12:10:09 +00:00
|
|
|
|
|
|
|
it 'orders ascending by default' do
|
|
|
|
ids = []
|
|
|
|
|
|
|
|
model.each_batch(of: 1) { |rel| ids.concat(rel.ids) }
|
|
|
|
|
|
|
|
expect(ids).to eq(ids.sort)
|
|
|
|
end
|
|
|
|
|
|
|
|
it 'accepts descending order' do
|
|
|
|
ids = []
|
|
|
|
|
|
|
|
model.each_batch(of: 1, order: :desc) { |rel| ids.concat(rel.ids) }
|
|
|
|
|
|
|
|
expect(ids).to eq(ids.sort.reverse)
|
|
|
|
end
|
2017-07-07 12:49:05 +00:00
|
|
|
end
|
|
|
|
end
|