PHPackages                             spatie/tabular-assertions - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Testing &amp; Quality](/categories/testing)
4. /
5. spatie/tabular-assertions

ActiveLibrary[Testing &amp; Quality](/categories/testing)

spatie/tabular-assertions
=========================

Write tabular assertions with Pest or PHPUnit

1.0.0(2y ago)57275.5k↓14.6%[1 PRs](https://github.com/spatie/tabular-assertions/pulls)MITPHPPHP ^8.2CI passing

Since Dec 29Pushed 1mo ago2 watchersCompare

[ Source](https://github.com/spatie/tabular-assertions)[ Packagist](https://packagist.org/packages/spatie/tabular-assertions)[ Docs](https://github.com/spatie/tabular-assertions)[ RSS](/packages/spatie-tabular-assertions/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (2)Dependencies (5)Versions (6)Used By (0)

Write tabular assertions with Pest or PHPUnit
=============================================

[](#write-tabular-assertions-with-pest-or-phpunit)

[![Latest Version on Packagist](https://camo.githubusercontent.com/b019f24dce3ab25abdf82e44fdf37955f8f911b5cb3c64cc4ca553ebeb47b88f/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7370617469652f746162756c61722d617373657274696f6e732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/spatie/tabular-assertions)[![GitHub Tests Action Status](https://camo.githubusercontent.com/3c37ec59bbf6ae49b6af43ca2d5b1ae918a1e7ad8ad3b7acd8af0c4fb4b7d057/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f7370617469652f746162756c61722d617373657274696f6e732f72756e2d74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/spatie/tabular-assertions/actions?query=workflow%3Arun-tests+branch%3Amain)[![GitHub Code Style Action Status](https://camo.githubusercontent.com/963b9d2314778aac5e6244a6b25288d3c46e3a3a8727dd734bcd97c1bf7c3c95/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f7370617469652f746162756c61722d617373657274696f6e732f6669782d7068702d636f64652d7374796c652d6973737565732e796d6c3f6272616e63683d6d61696e266c6162656c3d636f64652532307374796c65267374796c653d666c61742d737175617265)](https://github.com/spatie/tabular-assertions/actions?query=workflow%3A%22Fix+PHP+code+style+issues%22+branch%3Amain)[![Total Downloads](https://camo.githubusercontent.com/905553968ba8a9aa38a64df05aaaee4ba2471e9d1b16f2d12374ccc48109ba5c/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f7370617469652f746162756c61722d617373657274696f6e732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/spatie/tabular-assertions)

Tabular assertions allow you to describe data in a Markdown table-like format and compare it to the actual data. This is especially useful when comparing large, ordered data sets like financial data or a time series.

With Pest:

```
test('it compares a table', function () {
    $order = Order::factory()
        ->addItem('Pen', 2)
        ->addItem('Paper', 1)
        ->addItem('Pencil', 5)
        ->create();

    expect($order->items)->toMatchTable('
        | #id | #order_id | name   | quantity |
        |  #1 |        #1 | Pen    |        2 |
        |  #2 |        #1 | Paper  |        1 |
        |  #3 |        #1 | Pencil |        5 |
    ');
});
```

With PHPUnit:

```
use PHPUnit\Framework\TestCase;
use Spatie\TabularAssertions\PHPUnit\TabularAssertions;

class PHPUnitTest extends TestCase
{
    use TabularAssertions;

    public function test_it_contains_users(): void
    {
        $order = Order::factory()
            ->addItem('Pen', 2)
            ->addItem('Paper', 1)
            ->addItem('Pencil', 5)
            ->create();

        $this->assertMatchesTable('
            | #id | #order_id | name   | quantity |
            |  #1 |        #1 | Pen    |        2 |
            |  #2 |        #1 | Paper  |        1 |
            |  #3 |        #1 | Pencil |        5 |
        ', $order->items);
    }
}
```

Support us
----------

[](#support-us)

[![](https://camo.githubusercontent.com/3dcae39228df1b4bd60a5c2050cd10d35a39bd31a780e5a69c420ea03c744bc9/68747470733a2f2f6769746875622d6164732e73332e65752d63656e7472616c2d312e616d617a6f6e6177732e636f6d2f746162756c61722d617373657274696f6e732e6a70673f743d31)](https://spatie.be/github-ad-click/tabular-assertions)

We invest a lot of resources into creating [best in class open source packages](https://spatie.be/open-source). You can support us by [buying one of our paid products](https://spatie.be/open-source/support-us).

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on [our contact page](https://spatie.be/about-us). We publish all received postcards on [our virtual postcard wall](https://spatie.be/open-source/postcards).

Installation
------------

[](#installation)

You can install the package via composer:

```
composer require spatie/tabular-assertions
```

Why tabular assertions?
-----------------------

[](#why-tabular-assertions)

Tabular assertions have two major benefits over other testing strategies: expectations are optimized for readability &amp; failed assertions can display multiple errors at once.

**1. You can hand-write expectations that contain a lot of data and are optimized for readability.** Text-based tables are compact, allow you to compare the data in two dimensions.

The alternative would be to write multiple assertions.

```
expect($items[0]['order_id'])->toBe($order->id);
expect($items[0]['name'])->toBeDate('Pen');
expect($items[0]['quantity'])->toBe(2);

expect($items[1]['order_id'])->toBe($order->id);
expect($items[1]['name'])->toBeDate('Paper');
expect($items[1]['quantity'])->toBe(1);

// …
```

Expectations require you to assert each property individually. This makes it hard to see all dates at a glance, and is less readable in general.

Associative arrays require a lot of repetition with labels.

```
expect($items[0])->toBe([
    'order_id' => $order->id,
    'name' => 'Pen',
    'quantity' => 2,
]);

expect($items[1])->toBe([
    'order_id' => $order->id,
    'date' => 'Paper',
    'quantity' => 1,
]);

// …
```

Arrays without keys can't be aligned properly (manually maintained spaces would be striped by code style fixers). This becomes unclear when asserting multiple columns with different lengths.

```
expect($items)->toBe([
    [$order->id, 'Pen', 2],
    [$order->id, 'Paper', 1],
    // …
]);
```

With tabular assertions, we get a compact, readable overview of the data, and because it's stored in a single string code style fixers won't reformat it.

```
expect($items)->toMatchTable('
    | #id | #order_id | name   | quantity |
    |  #1 |        #1 | Pen    |        2 |
    |  #2 |        #1 | Paper  |        1 |
    |  #3 |        #1 | Pencil |        5 |
');
```

**2. Errors that can display multiple problems.** With separate expectations, tests fail on the first failed assertion which means you don't have the full picture (small issue vs. everything broken)

If you serialize two datasets to a table, you can get a nice output in a visual diff like PhpStorm's output when you use `assertEquals`.

In this assertions, you can see one value is wrong and one row is missing in one glance. With separate assertions, you only see the first error your test runner comes across.

[![CleanShot 2023-02-09 at 14 48 38@2x](https://user-images.githubusercontent.com/1561079/217830800-e88953a5-446b-49d1-be7d-edfbb5484441.png)](https://user-images.githubusercontent.com/1561079/217830800-e88953a5-446b-49d1-be7d-edfbb5484441.png)

This style of testing really shines when you have a lot of data to assert. This example has 9 rows and 9 columns, which means we're comparing 81 data points while keeping it all readable.

```
expect($order->logs)->toLookLike("
    | type        | reason   | #product_id | #tax_id | #shipping_id | #payment_id | price | paid  | refunded |
    | product     | created  |       #1    |         |              |             | 80_00 | 80_00 |     0_00 |
    | tax         | created  |       #1    |      #1 |              |             |  5_00 |  5_00 |     0_00 |
    | tax         | created  |       #1    |      #2 |              |             | 10_00 | 10_00 |     0_00 |
    | shipping    | created  |       #1    |         |           #1 |             |  5_00 |  5_00 |     0_00 |
    | product     | paid     |       #1    |         |              |          #1 |  0_00 |  0_00 |     2_00 |
    | tax         | paid     |       #1    |      #1 |              |          #1 |  0_00 |  0_00 |     0_00 |
    | tax         | paid     |       #1    |      #2 |              |          #1 |  0_00 |  0_00 |     0_00 |
    | shipping    | paid     |       #1    |         |           #1 |          #1 |  0_00 |  0_00 |     0_00 |
");
```

Usage
-----

[](#usage)

### Basic usage: Pest

[](#basic-usage-pest)

With Pest, the plugin will be autoloaded and readily available. Use the custom `toMatchTable()` expectation to compare data with a table.

### Basic usage: PHPUnit

[](#basic-usage-phpunit)

With PHPUnit, add the `Spatie\TabularAssertions\PHPUnit\TabularAssertions` trait to the tests you want to use tabular assertions with. Use `$this->assertMatchesTable()` to compare data with a table.

### Dynamic values

[](#dynamic-values)

Sometimes you want to compare data without actually comparing the exact value. For example, you want to assert that each person is in the same team, but don't know the team ID because the data is randomly seeded on every run. A column can be marked as "dynamic" by prefixing its name with a `#`. Dynamic columns will replace values with placeholders. A placeholder is unique for the value in the column. So a team with ID `123` would always be rendered as `#1`, another team `456` with `#2` etc.

For example, Sebastian &amp; Freek are in team Spatie which has a random ID, and Christoph is in team Laravel with another random ID.

```
| name      | #team_id |
| Sebastian |       #1 |
| Freek     |       #1 |
| Christoph |       #2 |

```

### Custom assertions

[](#custom-assertions)

Tabular assertions will cast the actual values to strings. We're often dealing with data more complex than stringables, in those cases it's worth creating a custom assertion method that prepares the data.

Consider the following example with a `User` model that has an `id`, `name`, and `date_of_birth` which will be cast to a `Carbon` object.

```
expect(User::all())->toMatchTable('
    | id | name       |       date_of_birth |
    |  1 | Sebastian  | 1992-02-01 00:00:00 |
');
```

Because `Carbon` objects automatically append seconds when stringified, our table becomes noisy. Instead, we'll create a custom `toMatchUsers` assertion to prepare our data before asserting.

```
expect()->extend('toMatchUsers', function (string $expected) {
    $users = $this->value->map(function (User $user) {
        return [
            'id' => $user->id,
            'name' => $user->name,
            'date_of_birth' => $user->date_of_birth->format('Y-m-d'),
        ];
    });

    expect($users)->toBe($expected);
});
```

```
expect(User::all())->toMatchTable('
    | id | name       | date_of_birth |
    |  1 | Sebastian  |    1992-02-01 |
');
```

In PHPUnit, this would be a custom assertion method.

```
class UserTest extends TestCase
{
    use TabularAssertions;

    private function assertMatchesUsers(string $expected, Collection $users): void
    {
        $users = $users->map(function (User $user) {
            return [
                'id' => $user->id,
                'name' => $user->name,
                'date_of_birth' => $user->date_of_birth->format('Y-m-d'),
            ];
        });

        $this->assertMatchesTable($expected, $users);
    }
}
```

This can also useful for any data transformations or truncations you want to do before asserting. Another example: `first_name` and `last_name` might be separate columns in the database, but in assertions they can be combined to reduce unnecessary whitespace in the table.

```
expect(User::all())->toMatchTable('
    | id | name                | date_of_birth |
    |  1 | Sebastian De Deyne  |    1992-02-01 |
');
```

```
expect()->extend('toMatchUsers', function (string $expected) {
    $users = $this->value->map(function (User $user) {
        return [
            'id' => $user->id,
            'name' => $user->first_name . ' ' . $user->last_name,
            'date_of_birth' => $user->date_of_birth->format('Y-m-d'),
        ];
    });

    expect($users)->toBe($expected);
});
```

Inspiration &amp; alternatives
------------------------------

[](#inspiration--alternatives)

The idea for this was inspired by Jest, which allows you to use a [table as a data provider](https://dev.to/andrewmcoupe/sit-down-at-my-jest-tagged-template-literal-table-and-tidy-up-your-tests-4f71).

[Snapshot testing](https://github.com/spatie/phpunit-snapshot-assertions) is also closely related to this. But snapshots aren't always optimized for readability, are stored in a separate file (not alongside the test), and are hard to write by hand (no TDD).

Testing
-------

[](#testing)

Tests are written with Pest. You can either use Pest's CLI or run `composer test` to run the suite.

```
composer test
```

In addition to tests, PhpStan statically analyses the code. Use `composer analyse` to run PhpStan.

```
composer analyse
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](CONTRIBUTING.md) for details.

Security Vulnerabilities
------------------------

[](#security-vulnerabilities)

Please review [our security policy](../../security/policy) on how to report security vulnerabilities.

Credits
-------

[](#credits)

- [Sebastian De Deyne](https://github.com/sebastiandedeyne)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

48

—

FairBetter than 95% of packages

Maintenance59

Moderate activity, may be stable

Popularity46

Moderate usage in the ecosystem

Community14

Small or concentrated contributor base

Maturity58

Maturing project, gaining track record

 Bus Factor2

2 contributors hold 50%+ of commits

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~9 days

Total

2

Last Release

862d ago

Major Versions

0.0.1 → 1.0.02024-01-08

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/7535935?v=4)[Spatie](/maintainers/spatie)[@spatie](https://github.com/spatie)

---

Top Contributors

[![sebastiandedeyne](https://avatars.githubusercontent.com/u/1561079?v=4)](https://github.com/sebastiandedeyne "sebastiandedeyne (24 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (13 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (9 commits)")[![freekmurze](https://avatars.githubusercontent.com/u/483853?v=4)](https://github.com/freekmurze "freekmurze (6 commits)")[![AlexVanderbist](https://avatars.githubusercontent.com/u/6287961?v=4)](https://github.com/AlexVanderbist "AlexVanderbist (2 commits)")[![Nielsvanpach](https://avatars.githubusercontent.com/u/10651054?v=4)](https://github.com/Nielsvanpach "Nielsvanpach (2 commits)")

---

Tags

pestphpphpunittestingspatietabular-assertions

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/spatie-tabular-assertions/health.svg)

```
[![Health](https://phpackages.com/badges/spatie-tabular-assertions/health.svg)](https://phpackages.com/packages/spatie-tabular-assertions)
```

###  Alternatives

[phpspec/prophecy

Highly opinionated mocking framework for PHP 5.3+

8.5k551.7M682](/packages/phpspec-prophecy)[spatie/temporary-directory

Easily create, use and destroy temporary directories

96889.9M206](/packages/spatie-temporary-directory)[brianium/paratest

Parallel testing for PHP

2.5k118.8M754](/packages/brianium-paratest)[spatie/phpunit-snapshot-assertions

Snapshot testing with PHPUnit

69617.9M510](/packages/spatie-phpunit-snapshot-assertions)[spatie/phpunit-watcher

Automatically rerun PHPUnit tests when source code changes

8839.2M475](/packages/spatie-phpunit-watcher)[orchestra/testbench

Laravel Testing Helper for Packages Development

2.2k39.1M32.1k](/packages/orchestra-testbench)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
