Testing a Publisher - messagebus/lapine GitHub Wiki

When using Lapine, you may not want to actually depend on RabbitMQ in your tests. Lapine provides test helpers to help test publishers using an in-memory message queue.

For information on testing consumers, see Testing a Consumer.

RSpec

The RSpec test helper can be included as follows:

require 'lapine/test/rspec_helper'

RSpec.configure do |config|
  config.include Lapine::Test::RSpecHelper, fake_rabbit: true

  config.before :each, :fake_rabbit do |example|
    Lapine::Test::RSpecHelper.setup(example)
  end

  config.after :each, :fake_rabbit do
    Lapine::Test::RSpecHelper.teardown
  end
end

This defines rspec tags that stub out the RabbitMQ layer. From here, you can bind a fake queue to the real exchange, then test that messages are published onto that fake queue. VERY IMPORTANT: the queue needs to be instantiated BEFORE any messages are published, otherwise the fake exchange will act very much like RabbitMQ, ie it will throw the message away.

RSpec.describe MyPublisher, fake_rabbit: true do
  let(:exchange) { Lapine.find_exchange('my.topic') }
  let!(:queue) { exchange.channel.queue.bind(exchange) }

  describe 'publishing' do
    it 'adds a message to a queue' do
      MyPublisher.new.publish('my.things')
      expect(queue.message_count).to eq(1)
    end

    it 'saves message for later introspection' do
      MyPublisher.new.publish('my.things')
      expect(queue.messages).to include(['{"omg":"lol"}', {routing_key: 'my.things'}])
    end
  end
end

Note that the fake_rabbit: true needs to be on the top level describe in order for RSpec to pick it up.