require 'unit_helper'
require 'stockman/publisher'

RSpec.describe Stockman::Publisher, type: :unit do
  describe '.publish' do
    let(:exchange_name) { nil }
    let(:routing_key) { double :routing_key }
    let(:message) { double :message }
    let(:bunny) { double :bunny }

    let(:exchange) { spy :exchange }
    let(:explicit_exchange) { spy :exchange }

    before do
      class_double('Bunny').as_stubbed_const

      amqp = double :amqp
      channel = double :channel

      allow(Stockman).to receive(:amqp).with(no_args).and_return(amqp)
      allow(Bunny).to receive(:new).with(amqp).and_return(bunny)
      allow(Stockman).to receive(:exchange).with(no_args).and_return(exchange_name)

      allow(bunny).to receive(:connected?).with(no_args)
        .and_return(true)

      allow(bunny).to receive(:start).with(no_args).once
      allow(bunny).to receive(:close).with(no_args).once

      allow(bunny).to receive(:create_channel).with(no_args)
        .and_return(channel).once
      allow(channel).to receive(:default_exchange).with(no_args)
        .and_return(exchange).once
      allow(channel).to receive(:exchange)
        .with(exchange_name, type: :topic, durable: true, auto_delete: false, arguments: { "alternate-exchange"=>"explicit_ae" })
        .and_return(explicit_exchange).once

      described_class.publish routing_key, message
      described_class.publish routing_key, message
    end

    after do
      described_class.reset!
    end

    it 'routes message to with given payload json' do
      expect(exchange).to have_received(:publish)
        .with(message, routing_key: routing_key, persistent: true).twice
    end

    context 'explicit exchange config' do
      let(:exchange_name) { 'explicit' }

      it 'routes message to specific exchange' do
        expect(explicit_exchange).to have_received(:publish)
          .with(message, routing_key: routing_key, persistent: true).twice
      end
    end
  end
end
