dbt tests in plain words, and why passing is not the same as correct
What dbt models and tests are, the four tests I reach for first, and what a green dbt build can and cannot tell you.
dbt is a tool that turns SQL select statements into tables and views in your warehouse, in the right order. Each select statement is called a model. A test is a rule the data must obey, and dbt checks it for you.
I use dbt in Maple, my civic data project, alongside DuckDB and Dagster. The project has 69 dbt models passing and 13 automated data quality checks.
The four tests I add first
dbt ships with four generic tests. You declare them in a YAML file next to the model:
models:
- name: permits
columns:
- name: permit_id
data_tests: [unique, not_null]
- name: status
data_tests:
- accepted_values:
values: ["issued", "closed", "cancelled"]
- name: city_id
data_tests:
- relationships:
to: ref("cities")
field: city_id
- unique: no two rows share this value. It protects the grain.
- not_null: the value is always present.
- accepted_values: only listed values appear.
- relationships: every value exists in another table, like a foreign key.
Custom tests
For rules that are specific to your data, you write a SQL query that returns the bad rows. If it returns nothing, the test passes. For example, "no building permit has an issue date in the future".
What a green build tells you
When dbt build reports every model and test passing, it means the SQL ran and the checks I wrote held. That is real information.
What it does not tell you
It does not tell you the data is right. Tests only check what I thought to check. If I never wrote a test for double counting, a fan-out will pass quietly. Passing means my rules held, not that I thought of all the rules.
So I treat the count as the start of the question. Which rules are missing? Where could the numbers be wrong without any test failing?
A habit that helps
When something breaks, I add a test for it before I fix it. The test now fails, I fix the model, and it passes. Over time the tests become a record of mistakes I have already made.
The project and its numbers are on my portfolio.