How to properly test a function that calls a GenServer.call?

For example. I have:

defmodule Account do 
  def create_user(attrs) do 
    SampleGenServer.create_user(attrs)
  end
end

defmodule SampleGenServer do 
  def start_link(_), do: ...

  def init(_), do: ...

  def create_user(attrs) do 
    GenServer.call(__MODULE__, {:create_user, attrs})
  end

  def handle_call({:create_user, attrs}, _from, state) do
    result = Repo.insert(attrs)

    {:reply, result, state}
  end
end

In test:

result = Account.create_user(attrs)
assert result == %{:ok, _}

But there’s always an exited error that says
** (exit) exited in: GenServer.call(SampleGenServer)
** (EXIT) time out

How to properly test Account.create_user? Any help would be appreciated. Thanks guys.

You need to start your GenServer first and prepare its state, or alternatively, call the handle_call/3 callback directly with a crafted state.

I mean the Account.create_user. Because I have coveralls for testing coverage and it won’t pass if I just test the Genserver.call directly. Any idea about the timeout error guys? I tried modifying the queue_target and queue_interval in config but still doesnt work.

Considering it fails with a timeout, it’s likely not the GenServer itself that is the problem, perhaps something is wrong with the Repo setup.

Besides that, %{:ok, _} is invalid syntax.

3 Likes

You’re right @aenglisc I have a Repo.transaction and that’s causing the “timeout”. Weird why transaction is like that. Anyway, Thanks guys!