Testing Configuration

Hey,

I’m really struggling to work this out, so I hope somebody can help.

I’ve got a PubSub module that can be sent messages through:

GenServer.cast :module, {:publish, %Event{}}

What it publishes too, can be configured through application config:

subscribers = Application.get_env :app, :subscribers, []

I’m trying to test that if the config contains ASubscriber, that ASubscriber actually receives a publish call.

I’ve tried many variations of assert_receive, but none seem to work. I’m not even sure when / how to load Application.get in the module (I’ve currently got it inside start_link) or how to provide Application.get_env for test.

If anyone has any suggestions, I’d love to hear them!

Thanks,
David

1 Like

In-case it helps, this is the actual module I wish to test:

defmodule PubSub do
  require Logger

  def start_link do
    Agent.start_link(fn -> MapSet.new end, name: __MODULE__)
    Enum.each(Application.get_env(:app, :subscribers, []), fn(subscriber) ->
        add_subscriber subscriber
    end)
  end

  def add_subscriber(subscriber) do
    Logger.debug("Adding a subscriber: #{inspect subscriber}")
    Agent.update(__MODULE__, &MapSet.put(&1, subscriber))
  end

  def publish(event = %Event{}) do
    Enum.each(Agent.get(__MODULE__, fn subscribers -> subscribers end),
      fn(subscriber) ->
        Logger.debug("Publishing to subscriber #{inspect subscriber}")
        GenServer.cast(subscriber, {:publish, event})
      end)
  end
end
1 Like