Test GenServer.cast in Espec tests

Hello!

I got a troubles with the testing of my GenServer.
I’m testing my GraphQL API. In the resolver of mutation I have a peace of code, which put some data to GenServer.cast and save entity to DB in async way. This entity has foreign key (user_id). As a results I get error ‘foreign_key_constraint’ all the time in my tests. After some debug I see that in this async process DB is empty. For me it looks like GenServer process run separately, out of test scope.

How can I solve this issue and check the full flow - sync resolver together with async genserver?

Thans in advance!

Hi there!

I found the reason of my issue and would like to share results here. The main problem - that my GenServer didn’t have access to Ecto.Adapters.SQL.Sandbox. I read official documentation and realized that I have the wrong mode of the sandbox in the spec_helper.exs file.

I had:

Ecto.Adapters.SQL.Sandbox.mode(MyApp.DB.Repo, {:shared, self()})

ESpec.configure fn(config) ->
  config.before fn(_tags) ->
    :ok = Ecto.Adapters.SQL.Sandbox.checkout(MyApp.DB.Repo)
  end

  config.finally fn(_shared) ->
    Ecto.Adapters.SQL.Sandbox.checkin(MyApp.DB.Repo, [])
  end
end

So I had to change it to:

ESpec.configure fn(config) ->
  config.before fn(_tags) ->
    :ok = Ecto.Adapters.SQL.Sandbox.checkout(MyApp.DB.Repo)

    Ecto.Adapters.SQL.Sandbox.mode(MyApp.DB.Repo, {:shared, self()})
  end

  config.finally fn(_shared) ->
    Ecto.Adapters.SQL.Sandbox.checkin(MyApp.DB.Repo, [])
  end
end

because mode function should go only after checkout.

2 Likes

Thanks for sharing the results really appreciated @rustemyusupov