Skip to main content

Black Friday 2025! Only until December 1st: coupon FRIDAY25 for 40% off Yearly/Lifetime membership!

Read more here

Pest Datasets

Premium
4 min read

In this section of the course, we will cover a few additional Pest functions that are not available in the same way in PHPUnit, or just work differently.

Topic of this lesson is datasets.

With datasets, you define an array of data and run tests multiple times with different subset of that data. Another use-case is to assign a name to a specific dataset and use it in multiple locations.


How to Use Datasets

Datasets are defined using the with() method and providing arguments in the function. Let's change the create product test to use the dataset.

tests/Feature/ProductsTest.php:

test('create product successful', function ($name, $price) {
$product = [
'name' => 'Product 123',
'price' => 1234
];
 
asAdmin()
->post('/products', $product)
->post('/products', ['name' => $name, 'price' => $price])
->assertStatus(302)
->assertRedirect('products');
 
$this->assertDatabaseHas('products', $product);
$this->assertDatabaseHas('products', ['name' => $name, 'price' => $price]);
 
$lastProduct = Product::latest()->first();
expect($name)->toBe($lastProduct->name)
->and($price)->toBe($lastProduct->price);
expect($product['name'])->toBe($lastProduct->name)
->and($product['price'])->toBe($lastProduct->price);
})->with([
['Product 1', 123],
['Product 2', 456],
]);

After running the test, we can see it is run two times, and the test adds to a name.

Every dataset can be...

The Full Lesson is Only for Premium Members

Want to access all of our courses? (29 h 14 min)

You also get:

54 courses
Premium tutorials
Access to repositories
Private Discord
Get Premium for $129/year or $29/month

Already a member? Login here

Comments & Discussion

G
genonline ✓ Link copied!

I needed to update the dataset code to get it to work.

dataset('products', function () { return [ ['name' => 'Product 1', 'price' => 123], ['name' => 'Product 2', 'price' => 453], ]; });

SP
Sylvain P ✓ Link copied!

Hello, does this mean we can use Pest and PHPUnit at the same time?

M
Modestas ✓ Link copied!

Yes, you can use pest and phpunit at the same time. But not in the same file/test.