Why do controller test require access to a database?

I am experimenting with a Phoenix backend and I’ve been a bit surprised by the fact that the tests require to access to a database.

I tend to prefer unit tests that are completely isolated to (integration?) tests that require a complex environment setup to run.

I was wondering what’s the reason Phoenix tests always try to reach for the database. Is this a byproduct of using Ecto as the persistence layer?

What do you mean? A controller doesn’t try to reach the database on its own. Don’t you have a call to the DB in your controller? :slight_smile:

1 Like

Can you show some code examples where it tends to be required?

If I generate a controller and a model with with
mix phoenix.gen.json # Generates a controller and model for a JSON based resource the resulting controller calls the database directly through Ecto and the related tests expects a test database to be present.

Creating it it’s not a big deal because Ecto sets it up itself, my main concern is that this way tests have a dependency on an external component when they could work as well with a mocked (or in memory) database.

Is there any reason behind requiring a real database for these tests?

1 Like