📎 Webclip
The Repository Pattern, Ecto, and Database-less Testing
The post explains the repository pattern as an abstraction between data models and persistence, then shows how Ecto uses that interface for inserts and queries. It argues that this separation makes the persistence layer swappable, which is useful for testing and for other setups like replicas.
Reading notes#
- The repository pattern sits between data models and the persistence layer, and Ecto uses that interface to perform database operations.
- An insert works by building a changeset, passing it to the repository, and letting the repository decide whether to write it.
- The
Userschema stays separate from the database, while the repository handles database-specific work. - The pattern is useful because data and persistence remain decoupled while still sharing a common interface.
- Ecto 3 split
ectoandecto_sql, withectofocused on mapping and validation andecto_sqlon database adapters. - A repository adapter can be swapped as long as it respects the same interface.
- This is helpful in tests when a real database is not practical.
- It also supports use cases like read/write replicas, since the model does not need to know where data comes from or goes to.
- The example app is an inventory system that uses Postgres in development and a mock repository in test.
- In the application supervisor, the Repo is started in non-test environments and skipped in
MIX_ENV=test. - Configuration sets
StoreInventory.Repoin development andStoreInventory.TestRepoin test. - The inventory schema defines
name,description,price, andquantity, with validations that require all fields and enforce positivepriceandquantity. - The main module uses
Application.get_env(:store_inventory, :repo)to choose which Repo module to call. insert_item/1inserts through the configured repo,all_items/0fetches all items, andaverage_item_price/0computes the mean price from the returned items.- The mock repo returns hard-coded items from
all/2and returns{:ok, struct(Item, values)}for valid changesets. - Invalid changesets are returned as
{:error, changeset}. - The tests check invalid insert errors, valid inserts, and the average price from the mocked data.
- The article closes by saying this pattern is useful when tests cannot easily run against a real database, while still recommending Ecto Sandbox for cases where a database is available.
