0
0
DbtHow-ToBeginner ยท 4 min read

How to Use dbt test: Syntax, Example, and Tips

Use dbt test to run tests defined in your dbt project that check data quality and integrity. Tests are written in YAML or SQL and executed with dbt test command to find data issues before deployment.
๐Ÿ“

Syntax

The basic syntax to run tests in dbt is dbt test. You can run all tests or specify a model or test name.

  • dbt test: Runs all tests in the project.
  • dbt test --models <model_name>: Runs tests only for the specified model.
  • dbt test --select <test_name>: Runs a specific test by name.

Tests are defined in your model's .yml files or as custom SQL tests.

bash
dbt test

dbt test --models customers

dbt test --select unique_customers_test
๐Ÿ’ป

Example

This example shows how to define and run a simple test that checks for unique values in a column.

In your models/customers.yml file, define a test for the customer_id column:

yaml
version: 2
models:
  - name: customers
    columns:
      - name: customer_id
        tests:
          - unique
          - not_null
๐Ÿ’ป

Example

Run the test with the command:

bash
dbt test --models customers
Output
Running with dbt=1.4.6 Found 1 model, 2 tests, 0 snapshots, 0 analyses, 0 macros, 0 operations, 0 seed files, 0 sources 12:00:00 | Concurrency: 1 threads 12:00:01 | 1 of 2 START test unique_customers_customer_id.................... [RUN] 12:00:02 | 1 of 2 PASS unique_customers_customer_id...................... [PASS in 1.0s] 12:00:02 | 2 of 2 START test not_null_customers_customer_id............... [RUN] 12:00:03 | 2 of 2 PASS not_null_customers_customer_id................... [PASS in 1.0s] Finished running 2 tests in 3.0s. Completed successfully
โš ๏ธ

Common Pitfalls

Common mistakes when using dbt test include:

  • Not defining tests in the .yml files, so dbt test has nothing to run.
  • Running tests without compiling models first, which can cause errors.
  • Ignoring test failures, which means data issues go unnoticed.
  • Using incorrect model or test names in the command line.

Always check test results and fix data issues before deploying.

bash
## Wrong: Running test on a non-existent model
# dbt test --models wrong_model

## Right: Run test on existing model
# dbt test --models customers
๐Ÿ“Š

Quick Reference

CommandDescription
dbt testRun all tests in the project
dbt test --models Run tests for a specific model
dbt test --select Run a specific test by name
Define tests in YAMLAdd tests under columns in model .yml files
Use built-in testsunique, not_null, accepted_values, relationships
โœ…

Key Takeaways

Use dbt test to run data quality checks defined in your project.
Define tests in your model YAML files under columns to check uniqueness, nulls, and more.
Run tests regularly to catch data issues early before deployment.
Specify models or tests in the command to run targeted checks.
Always review test results and fix failures promptly.