testing php applications
Pest Expectations
Pest expectations express assertions through expect($value) followed by methods such as toBe(), toEqual(), toContain(), or other type-appropriate checks. The goal remains precise, readable failures.
Use The Narrowest Expectation
Use toBe() when strict identity is important. Use expectations for strings, arrays, objects, exceptions, and collections according to the real contract. Chaining is useful when checks all describe the same value.
Do Not Turn Chains Into A Wall
A long chain can hide which business behaviour is under test. Split scenarios when setup or outcomes are conceptually different.
<?php
declare(strict_types=1);
$product = ['id' => 42, 'name' => 'Desk lamp'];
test('published product contains its public fields', function () use ($product): void {
expect($product)
->toHaveKeys(['id', 'name'])
->and($product['id'])->toBe(42)
->and($product['name'])->toBe('Desk lamp');
});
Common Mistakes
- Using loose equality when type matters.
- Chaining unrelated assertions into one hard-to-read test.
- Asserting implementation detail.
- Choosing fluent syntax over clear failure messages.
What To Practise
- Select precise Pest expectations.
- Use strict identity deliberately.
- Keep one behaviour per scenario.
Practice
Practice: Choose Product Expectations
Write the intended Pest expectations for a product result.
Requirements
- Check ID strictly.
- Check name.
- Check array keys.
- Keep expectations on the same returned product.
Show solution
The intended Pest assertions are concise and strict.
expect($product)
->toHaveKeys(['id', 'name'])
->and($product['id'])->toBe(42)
->and($product['name'])->toBe('Desk lamp');
Use the exact expectation methods supported by the installed Pest version and keep the chain focused.