Cleaning GenServer state between tests with ExUnit

Hello everyone.

I have a little problem testing GenServer with ExUnit. I have the following code…

  setup do
    Requests.list_requests
    |> Enum.each(fn request -> 
      Worker.stop(request) 
    end)
    # :sys.get_state Manager
    # :timer.sleep(1000)
    :ok
  end

The setup is to here ensure I clean all workers before each test. Worker.stop is a cast. If I add timer, it’s fine. If I remove it, there is race condition between my tests.

I usually transform cast to call with the help of :sys.get_state, that takes a name. But in this case I need to sync request workers, they are children of a dynamic_supervisor, they have no name, just a pid.

What would be the way to ensure cast has been executed before next test start? I mean, without the use of the ugly :timer.sleep?

Thanks for taking time.

In general I always just try to spawn a new genserver pid for each test case, so the stuff each test case does never affects any other test case.

4 Likes

Thank You for the response.

I tried to change cast to call, but it seems I still have race condition.

It’s ok to spawn a new GenServer, I will use factory data to solve this.

I still do not understand why the call is also running into race condition :slight_smile: