Testing with dbt
Use dbt's generic and singular data tests, packages like dbt-expectations, source freshness and unit tests to guard every model.
Intermediate · about 4 hours · difficulty 3/5
Learn first: Data Quality Fundamentals, dbt Fundamentals
If you use dbt, its testing features are the cheapest way to get broad coverage. Tests live next to models in YAML and run with dbt build.
Generic data tests
Declared on columns in YAML:
uniqueandnot_nullon every primary key. This single habit prevents most fan-out bugs.accepted_valuesfor status columns.relationshipsfor foreign keys (every order's customer exists in dim_customers).
Configure severity: warn or error, and thresholds like error_if: ">100".
Singular and custom tests
- Singular tests: a SQL file returning rows that violate a rule (orders where total does not equal sum of items). Zero rows means pass.
- Custom generic tests: write a parameterised test macro once, reuse it everywhere.
- Packages: dbt-utils (
unique_combination_of_columns,expression_is_true) and dbt-expectations (Great Expectations style checks in dbt).
Source freshness
Configure loaded_at_field and warn or error thresholds on sources; dbt source freshness alerts you when an upstream load is late.
Unit tests
dbt unit tests define mock input rows and expected output for a model, testing transformation logic without real data. Use them for tricky logic like SCD handling or currency conversion.
Running in CI
Run dbt build on every pull request so tests block bad changes, and in production so bad data stops before marts update. Store test failures with --store-failures for debugging.
Pitfalls
- Tests only on marts, so issues propagate through staging unnoticed.
- Setting everything to warn so nothing ever fails.
You are ready to move on when every model in your dbt project has primary key tests, key relationships are tested, sources have freshness checks, and one complex model has a unit test.
Key concepts
- unique and not_null
- accepted_values and relationships
- Severity and thresholds
- Singular tests
- Custom generic tests
- dbt-utils and dbt-expectations
- Source freshness
- dbt unit tests
Mini project
Add full test coverage to your dbt project: primary key tests on all models, relationship tests, accepted values, two singular business-rule tests, source freshness and one unit test. Break the data deliberately and show the failing test output.
Check yourself
Which two tests on a model's primary key catch most join fan-out bugs, and why?
Free resources
- dbt data tests (dbt Labs)
- dbt unit tests (dbt Labs)
- dbt source freshness (dbt Labs)