7. Testing GenServer `handle_call` - abarr/remote GitHub Wiki

I updated the user_fixtures.ex file to seed the sandbox.

"/test/support/fixtures/user_fixtures.ex"


defmodule Remote.UsersFixtures do
  @moduledoc """
  This module defines test helpers for creating
  entities via the `Remote.Users` context.
  """

  def seed_users(number, max, min) do
      Ecto.Adapters.SQL.query!(
      Remote.Repo,
      """
      INSERT INTO users (points, inserted_at, updated_at)
      SELECT floor(random() * (#{max} - #{min})) + #{min}, now() at time zone 'utc', now() at time zone 'utc'
      FROM generate_series(1, #{number});
      """
    )
  end
end

This can now be called with configurable min and max range values and the number of rows to create. I updated the test file to call the seed function in the setup.

"/test/remote/user_server_test.exs"

...
@update_interval 10_000
@limit 2
@test_number_users 100
@max 100
@min 0

setup do
  {:ok, user_server} =
    start_supervised(
      {
        Remote.Users.UserServer,
        name: __MODULE__,
        update_interval: @update_interval,
        users_returned_limit: @limit
      }
    )
  seed_users(@test_number_users, @max, @min)
  %{user_server: user_server}
end
...

Then I added a new test to confirm that the new handle_call to get users was working as expected

"/test/remote/user_server_test.exs"

...
test "get users limited by configuration and greater than max_number", %{user_server: user_server} do
  {%{max_number: max_number}, _} = GenServer.call(user_server, :get_state)

  %{users: users} = GenServer.call(user_server, :get_users_points_greater_than_max)

      assert Enum.count(users) == @limit

  for u <- users do
    assert u.points > max_number
  end
end
...

Running the tests confirms everything is working.

$ mix test

.....

Finished in 1.5 seconds (1.5s async, 0.00s sync)
5 tests, 0 failures

Randomized with seed 844451