require 'spec_helper' describe Hawkei::Processor::Worker do let(:state_worker) { Concurrent::AtomicBoolean.new(true) } let(:queue) { Queue.new } let(:worker) { Hawkei::Processor::Worker.new(queue, state_worker) } let!(:current_batch) { worker.instance_variable_get(:@batch) } describe 'private#add_message_to_batch' do context 'add to batch' do let(:message) { Object.new } before { worker.send(:add_message_to_batch, message) } it { expect(current_batch.messages).to eq([message]) } end context 'with batch full' do before do allow(current_batch).to receive(:full?).and_return(true) allow(worker).to receive(:flush) worker.send(:add_message_to_batch, Object.new) end it { expect(worker).to have_received(:flush) } end context 'call flush' do before do allow(worker).to receive(:flush) worker.send(:add_message_to_batch, Hawkei::Processor::Worker::FLUSH_MESSAGE) end it { expect(worker).to have_received(:flush) } end end describe 'private#flush' do before do allow(current_batch).to receive(:empty?).and_return(batch_status) allow(worker).to receive(:send_batch) worker.send(:flush) end context 'with not empty batch' do let(:batch_status) { false } it { expect(worker).to have_received(:send_batch).with(current_batch) } it { expect(current_batch).to_not eq(worker.instance_variable_get(:@batch)) } end context 'with empty batch' do let(:batch_status) { true } it { expect(worker).to_not have_received(:send_batch) } it { expect(current_batch).to eq(worker.instance_variable_get(:@batch)) } end end describe 'private#send_batch' do let(:batch) { Hawkei::Processor::Batch.new } let(:batch_can_retry) { true } before do allow(Hawkei::Request).to receive(:execute).and_return(response) allow(batch).to receive(:update_retry) allow(batch).to receive(:can_retry?).and_return(batch_can_retry) allow(Concurrent::ScheduledTask).to receive(:new) worker.send(:send_batch, batch) sleep(0.1) end context 'with valid request' do let(:response) { double('Hawkei::Request', body: "{\"object\":\"batch\",\"id\":41}") } it { expect(Hawkei::Request).to have_received(:execute) } it { expect(batch).to_not have_received(:update_retry) } it { expect(worker.instance_variable_get(:@promises).size).to eq(0) } end context 'with invalid request' do let(:response) { nil } it { expect(Hawkei::Request).to have_received(:execute) } it { expect(batch).to have_received(:update_retry) } it { expect(Concurrent::ScheduledTask).to have_received(:new) } it { expect(worker.instance_variable_get(:@promises).size).to eq(1) } end context 'with batch exhausted request' do let(:batch_can_retry) { false } let(:response) { nil } it { expect(Hawkei::Request).to have_received(:execute) } it { expect(batch).to have_received(:update_retry) } it { expect(Concurrent::ScheduledTask).to_not have_received(:new) } it { expect(worker.instance_variable_get(:@promises).size).to eq(0) } end end end