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...