TITLE: Basic Expectation in Pest PHP DESCRIPTION: Demonstrates a simple test using Pest's `test()` function and the `expect()` function with the `toBe()` expectation to assert that a value equals 3. SOURCE: https://github.com/pestphp/docs/blob/master/expectations.md#_snippet_0 LANGUAGE: php CODE: ``` test('sum', function () { $value = sum(1, 2); expect($value)->toBe(3); // Assert that the value is 3... }); ``` ---------------------------------------- TITLE: Define Global Teardown Callback (Pest PHP) DESCRIPTION: Use the `afterEach()` method in Pest PHP to define a callback function that will execute after every single test runs. This is useful for common cleanup tasks. SOURCE: https://github.com/pestphp/docs/blob/master/pest3-now-available.md#_snippet_19 LANGUAGE: php CODE: ``` afterEach(function () { // This will run after each test... }); ``` ---------------------------------------- TITLE: Advanced Architectural Testing with Pest DESCRIPTION: Showcases new architectural testing expectations in Pest 2.9, allowing assertions on classes within a namespace regarding strict types, naming conventions, readonly status, class/interface/trait type, final status, inheritance, and implemented interfaces. SOURCE: https://github.com/pestphp/docs/blob/master/pest-spicy-summer-release.md#_snippet_4 LANGUAGE: php CODE: ``` test('controllers') ->expect('App\Http\Controllers') ->toUseStrictTypes() ->toHaveSuffix('Controller') // or toHavePreffix, ... ->toBeReadonly() ->toBeClasses() // or toBeInterfaces, toBeTraits, ... ->classes->not->toBeFinal() // 🌶 ->classes->toExtendNothing() // or toExtend(Controller::class), ->classes->toImplementNothing() // or toImplement(ShouldQueue::class), ``` ---------------------------------------- TITLE: Run Pest PHP Tests (Bash) DESCRIPTION: Executes the Pest test runner to run the tests in the project's test suite. SOURCE: https://github.com/pestphp/docs/blob/master/installation.md#_snippet_2 LANGUAGE: bash CODE: ``` ./vendor/bin/pest ``` ---------------------------------------- TITLE: Basic beforeEach() Hook in Pest (PHP) DESCRIPTION: Shows the fundamental usage of the `beforeEach()` hook, which executes the provided closure before every test within the current file, typically used for necessary setup or configuration. SOURCE: https://github.com/pestphp/docs/blob/master/hooks.md#_snippet_1 LANGUAGE: php CODE: ``` beforeEach(function () { // Prepare something before each test run... }); ``` ---------------------------------------- TITLE: Checking Used Classes/Functions with Pest PHP (PHP) DESCRIPTION: The `toOnlyUse()` method guarantees that certain classes are restricted to using only specific functions or classes. The example checks that classes in the 'App\Models' namespace only use elements from the `Illuminate\Database` namespace. SOURCE: https://github.com/pestphp/docs/blob/master/arch-testing.md#_snippet_39 LANGUAGE: php CODE: ``` arch('models') ->expect('App\Models') ->toOnlyUse('Illuminate\Database'); ``` ---------------------------------------- TITLE: Prevent Namespace Use in Namespace with Pest PHP DESCRIPTION: Combining the `not` modifier with `toBeUsedIn()` restricts the usage of specific namespaces within another given namespace. SOURCE: https://github.com/pestphp/docs/blob/master/arch-testing.md#_snippet_16 LANGUAGE: PHP CODE: ``` arch('globals') ->expect('Illuminate\Http') ->not->toBeUsedIn('App\Domain'); ``` ---------------------------------------- TITLE: Require Pest PHP Dependency (Bash) DESCRIPTION: Removes PHPUnit (if present) and requires Pest as a development dependency using Composer, including all its dependencies. SOURCE: https://github.com/pestphp/docs/blob/master/installation.md#_snippet_0 LANGUAGE: bash CODE: ``` composer remove phpunit/phpunit composer require pestphp/pest --dev --with-all-dependencies ``` ---------------------------------------- TITLE: Writing a Basic Test with test() in Pest (PHP) DESCRIPTION: Shows how to define a simple test using Pest's `test()` function. It includes an example of calling a function and asserting the result using the `expect()` API. SOURCE: https://github.com/pestphp/docs/blob/master/writing-tests.md#_snippet_1 LANGUAGE: php CODE: ``` test('sum', function () { $result = sum(1, 2); expect($result)->toBe(3); }); ``` ---------------------------------------- TITLE: Basic Stress Test with Pest `stress()` Function (PHP) DESCRIPTION: Shows the fundamental usage of the `stress()` function within a Pest test. It performs a stress test on a given URL and then uses the result object to assert that the median request duration is below a specified threshold (100ms). SOURCE: https://github.com/pestphp/docs/blob/master/stress-testing.md#_snippet_3 LANGUAGE: PHP CODE: ``` requests()->duration()->med())->toBeLessThan(100); // < 100.00ms }); ``` ---------------------------------------- TITLE: Expectation: toHaveKeys(array $keys) in Pest PHP DESCRIPTION: This expectation ensures that the provided value (typically an array or object) contains all the specified keys. Dot notation can be used for nested keys. SOURCE: https://github.com/pestphp/docs/blob/master/expectations.md#_snippet_45 LANGUAGE: php CODE: ``` expect(['id' => 1, 'name' => 'Nuno'])->toHaveKeys(['id', 'name']); expect(['message' => ['from' => 'Nuno', 'to' => 'Luke'] ])->toHaveKeys(['message.from', 'message.to']); ``` ---------------------------------------- TITLE: Pest PHP Expectation: toContain() DESCRIPTION: This expectation ensures that all the given needles are elements of the value. It works for strings and arrays. SOURCE: https://github.com/pestphp/docs/blob/master/expectations.md#_snippet_14 LANGUAGE: php CODE: ``` expect('Hello World')->toContain('Hello'); expect('Pest: an elegant PHP Testing Framework')->toContain('Pest', 'PHP', 'Framework'); expect([1, 2, 3, 4])->toContain(2, 4); ``` ---------------------------------------- TITLE: Testing a simple function with Pest PHP DESCRIPTION: This snippet demonstrates a basic Pest test for a simple PHP function. It defines a `sum` function and then uses Pest's `test` function and `expect` assertion to verify that the function returns the correct result. SOURCE: https://github.com/pestphp/docs/blob/master/why-pest.md#_snippet_0 LANGUAGE: php CODE: ``` function sum($a, $b) { return $a + $b; } test('sum', function () { $result = sum(1, 2); expect($result)->toBe(3); }); ``` ---------------------------------------- TITLE: Pest Test with Expectation API (Before HOT) DESCRIPTION: A standard Pest PHP test using the Expectation API within a closure to create a user and assert its name. SOURCE: https://github.com/pestphp/docs/blob/master/higher-order-testing.md#_snippet_2 LANGUAGE: php CODE: ``` it('has a name', function () { $user = User::create([ 'name' => 'Nuno Maduro', ]); expect($user->name)->toBe('Nuno Maduro'); }); ``` ---------------------------------------- TITLE: Initialize Pest PHP (Bash) DESCRIPTION: Initializes Pest in the current PHP project, creating the necessary configuration file (Pest.php) at the root of the test suite. SOURCE: https://github.com/pestphp/docs/blob/master/installation.md#_snippet_1 LANGUAGE: bash CODE: ``` ./vendor/bin/pest --init ``` ---------------------------------------- TITLE: Basic Higher Order Expectations on Object - Pest PHP DESCRIPTION: This code demonstrates the basic syntax of Higher Order Expectations in Pest PHP. Expectations are chained directly onto the `expect()` function, accessing properties (`->name`, `->surname`) or calling methods (`->addTitle('Mr.')`) on the underlying value (`$user`) before applying the expectation (`->toBe(...)`). SOURCE: https://github.com/pestphp/docs/blob/master/higher-order-testing.md#_snippet_8 LANGUAGE: php CODE: ``` expect($user) ->name->toBe('Nuno') ->surname->toBe('Maduro') ->addTitle('Mr.')->toBe('Mr. Nuno Maduro'); ``` ---------------------------------------- TITLE: Running Specific Test with Pest only() (PHP) DESCRIPTION: Illustrates the use of the only() method appended to a test definition within a PHP file to mark that specific test as the only one to be executed when the suite runs. SOURCE: https://github.com/pestphp/docs/blob/master/filtering-tests.md#_snippet_7 LANGUAGE: php CODE: ``` test('sum', function () { $result = sum(1, 2); expect($result)->toBe(3); })->only(); ``` ---------------------------------------- TITLE: Define Shared Pest Helper Function (PHP) DESCRIPTION: Shows how to define a helper function `mockPayments` in a file like `tests/Pest.php` or `tests/Helpers.php` for use across multiple test files. This example demonstrates mocking a payment client within the helper and using the returned mock object in a test case. SOURCE: https://github.com/pestphp/docs/blob/master/custom-helpers.md#_snippet_1 LANGUAGE: php CODE: ``` use App\Clients\PaymentClient; use Mockery; // tests/Pest.php or tests/Helpers.php function mockPayments(): object { $client = Mockery::mock(PaymentClient::class); // return $client; } // tests/Feature/PaymentsTest.php it('may buy a book', function () { $client = mockPayments(); // }) ``` ---------------------------------------- TITLE: Defining Global beforeEach Hook for All Tests (Pest PHP) DESCRIPTION: This snippet defines a global beforeEach hook in Pest.php that runs before every single test in the suite. This is useful for general setup tasks that apply universally, such as basic application bootstrapping or database state preparation. SOURCE: https://github.com/pestphp/docs/blob/master/global-hooks.md#_snippet_1 LANGUAGE: php CODE: ``` pest()->beforeEach(function () { // Interact with your database... }); ``` ---------------------------------------- TITLE: Filtering Tests by Pattern with Pest (Bash) DESCRIPTION: Shows how to use the --filter option with a regular expression pattern to execute only tests whose description or related output matches the pattern. SOURCE: https://github.com/pestphp/docs/blob/master/filtering-tests.md#_snippet_3 LANGUAGE: bash CODE: ``` ./vendor/bin/pest --filter "test description" ``` ---------------------------------------- TITLE: Pest PHP Expectation: toBeLessThanOrEqual() DESCRIPTION: This expectation ensures that the value is less than or equal to the expected value. SOURCE: https://github.com/pestphp/docs/blob/master/expectations.md#_snippet_13 LANGUAGE: php CODE: ``` expect($count)->toBeLessThanOrEqual(2); ``` ---------------------------------------- TITLE: Defining Multiple Architecture Rules with Pest PHP DESCRIPTION: This snippet demonstrates how to define various architectural rules using Pest PHP's `arch()` function. It shows examples of enforcing strict types, restricting function usage, checking class types and inheritance, controlling usage dependencies, and applying predefined presets for common PHP and security checks. SOURCE: https://github.com/pestphp/docs/blob/master/arch-testing.md#_snippet_0 LANGUAGE: PHP CODE: ``` arch() ->expect('App') ->toUseStrictTypes() ->not->toUse(['die', 'dd', 'dump']); arch() ->expect('App\Models') ->toBeClasses() ->toExtend('Illuminate\Database\Eloquent\Model') ->toOnlyBeUsedIn('App\Repositories') ->ignoring('App\Models\User'); arch() ->expect('App\Http') ->toOnlyBeUsedIn('App\Http'); arch() ->expect('App\*\Traits') ->toBeTraits(); arch()->preset()->php(); arch()->preset()->security()->ignoring('md5'); ``` ---------------------------------------- TITLE: Enforcing Minimum Coverage Threshold DESCRIPTION: This Bash command shows how to run tests with coverage and enforce a minimum percentage threshold. If the overall coverage falls below the specified percentage (e.g., 90), the test run will fail. SOURCE: https://github.com/pestphp/docs/blob/master/test-coverage.md#_snippet_2 LANGUAGE: Bash CODE: ``` ./vendor/bin/pest --coverage --min=90 ``` ---------------------------------------- TITLE: Pest Test with Expectation API and Higher Order Testing DESCRIPTION: Applies Higher Order Testing to a Pest PHP test using the Expectation API. The expectation value is lazily evaluated using a closure passed to the `expect()` method, chained directly to `it()`. SOURCE: https://github.com/pestphp/docs/blob/master/higher-order-testing.md#_snippet_3 LANGUAGE: php CODE: ``` it('has a name') ->expect(fn () => User::create(['name' => 'Nuno Maduro'])->name) ->toBe('Nuno Maduro'); ``` ---------------------------------------- TITLE: Running Pest Tests in Parallel (Bash) DESCRIPTION: Executes the Pest test suite using the --parallel option to run tests concurrently across multiple processes, significantly reducing execution time by utilizing available CPU cores. SOURCE: https://github.com/pestphp/docs/blob/master/optimizing-tests.md#_snippet_0 LANGUAGE: bash CODE: ``` ./vendor/bin/pest --parallel ``` ---------------------------------------- TITLE: Executing Pest Tests by Group via CLI DESCRIPTION: This command shows how to run only the tests that have been assigned to a specific group (`feature`) using the Pest command-line interface. This allows for selective execution of test suites. SOURCE: https://github.com/pestphp/docs/blob/master/grouping-tests.md#_snippet_1 LANGUAGE: bash CODE: ``` ./vendor/bin/pest --group=feature ``` ---------------------------------------- TITLE: Throwing Exceptions with andThrow DESCRIPTION: This snippet demonstrates how to configure a mocked method to throw a specific exception when it is called, using the `andThrow()` method. SOURCE: https://github.com/pestphp/docs/blob/master/mocking.md#_snippet_6 LANGUAGE: php CODE: ``` $client->shouldReceive('post')->andThrow(new Exception); ``` ---------------------------------------- TITLE: Pest PHP Expectation: toBeFalse() DESCRIPTION: This expectation ensures that the value is strictly boolean false. SOURCE: https://github.com/pestphp/docs/blob/master/expectations.md#_snippet_8 LANGUAGE: php CODE: ``` expect($isPublished)->toBeFalse(); ``` ---------------------------------------- TITLE: Profile Slowest Tests (Shell) DESCRIPTION: Outputs the top ten slowest tests to standard output for performance analysis. SOURCE: https://github.com/pestphp/docs/blob/master/cli-api-reference.md#_snippet_32 LANGUAGE: Shell CODE: ``` --profile ``` ---------------------------------------- TITLE: Expecting Exception Class and Message in Pest PHP DESCRIPTION: Provide a second argument to the `throws()` method to assert that the thrown exception is of a specific class and has a specific message. SOURCE: https://github.com/pestphp/docs/blob/master/exceptions.md#_snippet_1 LANGUAGE: php CODE: ``` it('throws exception', function () { throw new Exception('Something happened.'); })->throws(Exception::class, 'Something happened.'); ``` ---------------------------------------- TITLE: Asserting No Exceptions with Pest PHP DESCRIPTION: Use the `throwsNoExceptions()` method to assert that the test closure completes without throwing any exceptions. SOURCE: https://github.com/pestphp/docs/blob/master/exceptions.md#_snippet_6 LANGUAGE: php CODE: ``` it('throws no exceptions', function () { $result = 1 + 1; })->throwsNoExceptions(); ``` ---------------------------------------- TITLE: Cleaning Properties with afterEach() in Pest (PHP) DESCRIPTION: Demonstrates how `afterEach()` can be used to clean up resources or reset state associated with properties initialized in `beforeEach()`, ensuring a clean state between tests and preventing interference. SOURCE: https://github.com/pestphp/docs/blob/master/hooks.md#_snippet_4 LANGUAGE: php CODE: ``` afterEach(function () { $this->userRepository->reset(); }); ``` ---------------------------------------- TITLE: Configure Pest Tests in GitLab CI/CD (YAML) DESCRIPTION: This YAML configuration defines a GitLab CI/CD pipeline (`.gitlab-ci.yml`) with stages for building dependencies and running tests. The `build:vendors` job installs Composer dependencies, and the `tests` job executes the Pest test suite using `./vendor/bin/pest --ci`. Both jobs are triggered on merge requests and pushes. SOURCE: https://github.com/pestphp/docs/blob/master/continuous-integration.md#_snippet_1 LANGUAGE: YAML CODE: ``` stages: - build - test build:vendors: stage: build only: refs: - merge_requests - push cache: key: files: - composer.lock policy: pull-push image: composer:2 script: - composer install --no-interaction --prefer-dist --optimize-autoloader tests: stage: test only: refs: - merge_requests - push cache: key: files: - composer.lock policy: pull image: php:8.2 script: - ./vendor/bin/pest --ci ``` ---------------------------------------- TITLE: Dump And Die With Dd Modifier Pest PHP PHP DESCRIPTION: Dumps the current expectation value and halts execution, useful for debugging. Can be applied directly to an expectation or within sequence/each closures. Takes no arguments. SOURCE: https://github.com/pestphp/docs/blob/master/expectations.md#_snippet_73 LANGUAGE: php CODE: ``` expect(14)->dd(); // 14 expect([1, 2])->sequence( fn ($number) => $number->toBe(1), fn ($number) => $number->dd(), // 2 ); ``` ---------------------------------------- TITLE: Pest PHP Expectation: toBe() DESCRIPTION: This expectation ensures that both the value and the expected value share the same type and value. When used with objects, it verifies that both variables reference the exact same object. SOURCE: https://github.com/pestphp/docs/blob/master/expectations.md#_snippet_3 LANGUAGE: php CODE: ``` expect(1)->toBe(1); expect('1')->not->toBe(1); expect(new StdClass())->not->toBe(new StdClass()); ``` ---------------------------------------- TITLE: Generate Code Coverage Report (Shell) DESCRIPTION: Generates a code coverage report and outputs it to standard output. SOURCE: https://github.com/pestphp/docs/blob/master/cli-api-reference.md#_snippet_0 LANGUAGE: Shell CODE: ``` --coverage ``` ---------------------------------------- TITLE: Argument Expectations with with and any DESCRIPTION: This snippet shows how to specify expected arguments for a mocked method call using the `with()` method. It also demonstrates using `Mockery::any()` as a wildcard matcher for arguments. Mockery throws an exception if the method is called with arguments that do not match the expectation. SOURCE: https://github.com/pestphp/docs/blob/master/mocking.md#_snippet_2 LANGUAGE: php CODE: ``` $client->shouldReceive('post') ->with($firstArgument, $secondArgument); ``` LANGUAGE: php CODE: ``` $client->shouldReceive('post') ->with($firstArgument, Mockery::any()); ``` ---------------------------------------- TITLE: Example Pest Test (After Drift) DESCRIPTION: Shows the equivalent test written in the Pest syntax, demonstrating the conversion result from the PHPUnit example. SOURCE: https://github.com/pestphp/docs/blob/master/migrating-from-phpunit-guide.md#_snippet_3 LANGUAGE: php CODE: ``` test('true is true', function () { expect(true)->toBeTrue(); }); ``` ---------------------------------------- TITLE: Defining Global beforeEach Hook for Specific Group/Folder (Pest PHP) DESCRIPTION: This snippet defines a global beforeEach hook within the Pest.php configuration file. It will execute before each test case that extends TestCase, is part of the 'integration' group, and is located within the 'Feature' directory. It's typically used for setup tasks like database interactions specific to certain test subsets. SOURCE: https://github.com/pestphp/docs/blob/master/global-hooks.md#_snippet_0 LANGUAGE: php CODE: ``` pest()->extend(TestCase::class)->beforeEach(function () { // Interact with your database... })->group('integration')->in('Feature'); ``` ---------------------------------------- TITLE: Override Expectation for Specific Type (Pest PHP) DESCRIPTION: The `intercept()` method allows replacing an existing expectation's behavior entirely for values of a specific type. This example overrides the `toBe()` expectation for `Illuminate\Database\Eloquent\Model` instances to compare them by their `id` property instead of strict object identity. SOURCE: https://github.com/pestphp/docs/blob/master/custom-expectations.md#_snippet_3 LANGUAGE: php CODE: ``` use Illuminate\Database\Eloquent\Model; use App\Models\User; // tests/Pest.php or tests/Expectations.php expect()->intercept('toBe', Model::class, function(Model $expected) { expect($this->value->id)->toBe($expected->id); }); // tests/Feature/ExampleTest.php test('models', function () { $userA = User::find(1); $userB = User::find(1); expect($userA)->toBe($userB); }); ``` ---------------------------------------- TITLE: Expectation: toThrow() in Pest PHP DESCRIPTION: This expectation ensures that a given closure throws an exception. It can optionally check for a specific exception class, a specific exception message, or both. It can also check against an instance of an exception. SOURCE: https://github.com/pestphp/docs/blob/master/expectations.md#_snippet_53 LANGUAGE: php CODE: ``` expect(fn() => throw new Exception('Something happened.'))->toThrow(Exception::class); expect(fn() => throw new Exception('Something happened.'))->toThrow('Something happened.'); expect(fn() => throw new Exception('Something happened.'))->toThrow(Exception::class, 'Something happened.'); expect(fn() => throw new Exception('Something happened.'))->toThrow(new Exception('Something happened.')); ``` ---------------------------------------- TITLE: Basic beforeAll() Hook in Pest (PHP) DESCRIPTION: Shows the fundamental usage of the `beforeAll()` hook, which executes the provided closure once before any tests are run within the current file, typically for setup that applies to all tests. Note that the `$this` variable is not available. SOURCE: https://github.com/pestphp/docs/blob/master/hooks.md#_snippet_6 LANGUAGE: php CODE: ``` beforeAll(function () { // Prepare something once before any of this file's tests run... }); ``` ---------------------------------------- TITLE: Pest PHP Expectation: toContainOnlyInstancesOf() DESCRIPTION: This expectation ensures that the value, which must be an array, contains only instances of the specified class. SOURCE: https://github.com/pestphp/docs/blob/master/expectations.md#_snippet_16 LANGUAGE: php CODE: ``` $dates = [new DateTime(), new DateTime()]; expect($dates)->toContainOnlyInstancesOf(DateTime::class); ``` ---------------------------------------- TITLE: Dump And Die Conditionally With DdWhen Modifier Pest PHP PHP DESCRIPTION: Dumps the current expectation value and halts execution only when the provided condition is truthy. Takes a boolean condition or a closure returning a boolean as input. Useful for conditional debugging. SOURCE: https://github.com/pestphp/docs/blob/master/expectations.md#_snippet_74 LANGUAGE: php CODE: ``` expect([1, 2])->each( fn ($number) => $number->ddWhen(fn (int $number) => $number === 2) // 2 ); ``` ---------------------------------------- TITLE: Set Minimum Code Coverage (Shell) DESCRIPTION: Sets the minimum required code coverage percentage and causes the test run to fail if the threshold is not met. SOURCE: https://github.com/pestphp/docs/blob/master/cli-api-reference.md#_snippet_1 LANGUAGE: Shell CODE: ``` --coverage --min= ``` ---------------------------------------- TITLE: Grouping Tests with describe() in Pest (PHP) DESCRIPTION: Demonstrates how to use the `describe()` function to group related tests together. This helps organize test suites and provides a clearer structure in the test output. SOURCE: https://github.com/pestphp/docs/blob/master/writing-tests.md#_snippet_3 LANGUAGE: php CODE: ``` describe('sum', function () { it('may sum integers', function () { $result = sum(1, 2); expect($result)->toBe(3); }); it('may sum floats', function () { $result = sum(1.5, 2.5); expect($result)->toBe(4.0); }); }); ``` ---------------------------------------- TITLE: Skipping a Pest PHP Test Conditionally (Boolean) DESCRIPTION: Illustrates skipping a test based on a boolean condition passed as the first argument to the `skip()` method. The test is skipped only if the condition is true. SOURCE: https://github.com/pestphp/docs/blob/master/skipping-tests.md#_snippet_2 LANGUAGE: php CODE: ``` it('has home', function () { // })->skip($condition == true, 'temporarily unavailable'); ``` ---------------------------------------- TITLE: Enforcing Strict Equality with Pest PHP Architecture DESCRIPTION: This code demonstrates the `toUseStrictEquality` method, which ensures that all files within the specified namespace (`App`) use the strict equality operator (`===`) instead of the loose equality operator (`==`). This promotes safer type comparisons. SOURCE: https://github.com/pestphp/docs/blob/master/arch-testing.md#_snippet_43 LANGUAGE: php CODE: ``` arch('models') ->expect('App') ->toUseStrictEquality(); ``` ---------------------------------------- TITLE: Use Namespaced Laravel Functions with Authentication DESCRIPTION: Example showing how to use the namespaced `actingAs()` function from `Pest\Laravel` to authenticate a user before making an HTTP request to a protected route in a test. SOURCE: https://github.com/pestphp/docs/blob/master/plugins.md#_snippet_9 LANGUAGE: php CODE: ``` use App\Models\User; use function Pest\Laravel\{actingAs}; test('authenticated user can access the dashboard', function () { $user = User::factory()->create(); actingAs($user)->get('/dashboard') ->assertStatus(200); }); ``` ---------------------------------------- TITLE: Defining Return Values with andReturn DESCRIPTION: This snippet shows how to specify the value a mocked method should return using `andReturn()`. It also demonstrates providing multiple arguments to `andReturn()` to define a sequence of return values for successive calls. SOURCE: https://github.com/pestphp/docs/blob/master/mocking.md#_snippet_4 LANGUAGE: php CODE: ``` $client->shouldReceive('post')->andReturn('post response'); ``` LANGUAGE: php CODE: ``` $client->shouldReceive('post')->andReturn(1, 2); $client->post(); // int(1) $client->post(); // int(2) ``` ---------------------------------------- TITLE: Apply Expectation To Each Item With Each Modifier Pest PHP PHP DESCRIPTION: Applies the subsequent expectation or a provided closure to each item of the expected iterable value. Takes an iterable or a closure as input. Useful for asserting properties of all elements in a collection. SOURCE: https://github.com/pestphp/docs/blob/master/expectations.md#_snippet_76 LANGUAGE: php CODE: ``` expect([1, 2, 3])->each->toBeInt(); expect([1, 2, 3])->each->not->toBeString(); expect([1, 2, 3])->each(fn ($number) => $number->toBeLessThan(4)); ``` ---------------------------------------- TITLE: Using the Not Modifier in Pest PHP DESCRIPTION: Illustrates how to use the `not` modifier to negate expectations, asserting that a value is *not* of a certain type or value. SOURCE: https://github.com/pestphp/docs/blob/master/expectations.md#_snippet_2 LANGUAGE: php CODE: ``` expect($value) ->toBeInt() ->toBe(3) ->not->toBeString() // Not to be string... ->not->toBe(4); // Not to be 4... ``` ---------------------------------------- TITLE: Chaining Expectations in Pest PHP DESCRIPTION: Shows how to chain multiple expectations (`toBeInt`, `toBe`) on a single value using Pest's expectation API for more comprehensive assertions. SOURCE: https://github.com/pestphp/docs/blob/master/expectations.md#_snippet_1 LANGUAGE: php CODE: ``` expect($value) ->toBeInt() ->toBe(3); ``` ---------------------------------------- TITLE: Scoping Hooks with describe() in Pest (PHP) DESCRIPTION: Demonstrates how Pest hooks, such as `beforeEach()`, can be included within `describe()` functions to limit their execution scope to a specific group of tests, showing the nesting structure. SOURCE: https://github.com/pestphp/docs/blob/master/hooks.md#_snippet_0 LANGUAGE: php CODE: ``` beforeEach(function () { // }); describe('something', function () { beforeEach(function () { // }); // describe('something else', function () { beforeEach(function () { // }); // }); }); test('something', function () { // }); ``` ---------------------------------------- TITLE: Scoped Higher Order Expectations - Pest PHP DESCRIPTION: This example introduces Scoped Higher Order Expectations using the `->scoped()` method. This method takes a closure, allowing you to perform a set of chained expectations on a nested property or the result of a method call (like `->address()`) without breaking the main expectation chain on the parent object (`$user`). This is particularly useful for checking properties of related objects in models. SOURCE: https://github.com/pestphp/docs/blob/master/higher-order-testing.md#_snippet_11 LANGUAGE: php CODE: ``` expect($user) ->name->toBe('Nuno') ->email->toBe('enunomaduro@gmail.com') ->address()->scoped(fn ($address) => $address ->line1->toBe('1 Pest Street') ->city->toBe('Lisbon') ->country->toBe('Portugal') ); ``` ---------------------------------------- TITLE: Use Pest Faker Plugin DESCRIPTION: Example demonstrating how to use the namespaced `fake()` function provided by the Pest Faker plugin to generate random data within a test closure. SOURCE: https://github.com/pestphp/docs/blob/master/plugins.md#_snippet_1 LANGUAGE: php CODE: ``` use function Pest\Faker\fake; it('generates a name', function () { $name = fake()->name; // random name... // }); ``` ---------------------------------------- TITLE: Higher Order Expectations on Arrays - Pest PHP DESCRIPTION: This example shows how Higher Order Expectations can be used with arrays. Array keys can be accessed directly (`->name`, `->projects`, `->{0}`) to perform expectations on their values. It also demonstrates the use of the `->each` method to apply an expectation to every element in an array. SOURCE: https://github.com/pestphp/docs/blob/master/higher-order-testing.md#_snippet_9 LANGUAGE: php CODE: ``` expect(['name' => 'Nuno', 'projects' => ['Pest', 'OpenAI', 'Laravel Zero']]) ->name->toBe('Nuno') ->projects->toHaveCount(3) ->each->toBeString(); expect(['Dan', 'Luke', 'Nuno']) ->{0}->toBe('Dan'); ``` ---------------------------------------- TITLE: Pest PHP Expectation: toHaveProperty() DESCRIPTION: This expectation ensures that the value has a property with the specified name. Optionally, you can provide a second argument to verify the property's value. SOURCE: https://github.com/pestphp/docs/blob/master/expectations.md#_snippet_18 LANGUAGE: php CODE: ``` expect($user)->toHaveProperty('name'); expect($user)->toHaveProperty('name', 'Nuno'); expect($user)->toHaveProperty('is_active', 'true'); ``` ---------------------------------------- TITLE: Ignoring Namespaces in BeforeEach (PHP) DESCRIPTION: Configures Pest's architecture checks within a beforeEach hook to ignore code within the 'Illuminate' namespace and global functions, focusing checks on application dependencies. SOURCE: https://github.com/pestphp/docs/blob/master/arch-testing.md#_snippet_61 LANGUAGE: php CODE: ``` // tests/Pest.php pest()->beforeEach(function () { $this->arch()->ignore([ 'Illuminate', ])->ignoreGlobalFunctions(); }); ``` ---------------------------------------- TITLE: Setting Exact Method Call Counts with Mockery in PHP DESCRIPTION: Demonstrates setting exact expectations for method call counts using `once()`, `twice()`, and `times()` methods on a Mockery mock object. SOURCE: https://github.com/pestphp/docs/blob/master/mocking.md#_snippet_7 LANGUAGE: php CODE: ``` $mock->shouldReceive('post')->once(); $mock->shouldReceive('put')->twice(); $mock->shouldReceive('delete')->times(3); // ... ``` ---------------------------------------- TITLE: Pest PHP Expectation: toBeTrue() DESCRIPTION: This expectation ensures that the value is strictly boolean true. SOURCE: https://github.com/pestphp/docs/blob/master/expectations.md#_snippet_6 LANGUAGE: php CODE: ``` expect($isPublished)->toBeTrue(); ``` ---------------------------------------- TITLE: Pest PHP Expectation: toBeBetween() DESCRIPTION: This expectation ensures that the value is between two other values. It supports integer, float, and DateTime types. SOURCE: https://github.com/pestphp/docs/blob/master/expectations.md#_snippet_4 LANGUAGE: php CODE: ``` expect(2)->toBeBetween(1, 3); expect(1.5)->toBeBetween(1, 2); $expectationDate = new DateTime('2023-09-22'); $oldestDate = new DateTime('2023-09-21'); $latestDate = new DateTime('2023-09-23'); expect($expectationDate)->toBeBetween($oldestDate, $latestDate); ``` ---------------------------------------- TITLE: Generating Basic Test Coverage Report DESCRIPTION: This Bash command demonstrates how to run the Pest test suite and generate a basic code coverage report using the --coverage option. This requires a coverage driver like XDebug or PCOV to be installed and configured. SOURCE: https://github.com/pestphp/docs/blob/master/test-coverage.md#_snippet_1 LANGUAGE: Bash CODE: ``` ./vendor/bin/pest --coverage ``` ---------------------------------------- TITLE: Running Mutation Tests (Bash) DESCRIPTION: Execute Pest PHP from your project's vendor directory using the `--mutate` option to start the mutation testing process. Add the `--parallel` option to speed up execution by running tests concurrently. SOURCE: https://github.com/pestphp/docs/blob/master/mutation-testing.md#_snippet_1 LANGUAGE: bash CODE: ``` ./vendor/bin/pest --mutate # or in parallel... ./vendor/bin/pest --mutate --parallel ``` ---------------------------------------- TITLE: Running Pest Tests in Parallel with Custom Processes (Bash) DESCRIPTION: Executes the Pest test suite in parallel, explicitly setting the number of processes to use with the --processes option, overriding the default behavior of using available CPU cores. SOURCE: https://github.com/pestphp/docs/blob/master/optimizing-tests.md#_snippet_1 LANGUAGE: bash CODE: ``` ./vendor/bin/pest --parallel --processes=10 ``` ---------------------------------------- TITLE: Using Basic Datasets in Pest PHP DESCRIPTION: Demonstrates how to use a simple inline dataset with a single argument in a Pest PHP test, automatically running the test for each value provided in the array. SOURCE: https://github.com/pestphp/docs/blob/master/datasets.md#_snippet_0 LANGUAGE: php CODE: ``` it('has emails', function (string $email) { expect($email)->not->toBeEmpty(); })->with(['enunomaduro@gmail.com', 'other@example.com']); ``` ---------------------------------------- TITLE: Pest PHP Expectation: toBeEmpty() DESCRIPTION: This expectation ensures that the value is empty. It works for strings, arrays, and null. SOURCE: https://github.com/pestphp/docs/blob/master/expectations.md#_snippet_5 LANGUAGE: php CODE: ``` expect('')->toBeEmpty(); expect([])->toBeEmpty(); expect(null)->toBeEmpty(); ``` ---------------------------------------- TITLE: Pest PHP Expectation: toHaveCount() DESCRIPTION: This expectation ensures that the provided count matches the number of elements in an iterable value. SOURCE: https://github.com/pestphp/docs/blob/master/expectations.md#_snippet_17 LANGUAGE: php CODE: ``` expect(['Nuno', 'Luke', 'Alex', 'Dan'])->toHaveCount(4); ``` ---------------------------------------- TITLE: Defining Scoped Dataset in Pest PHP DESCRIPTION: This snippet shows how to define a dataset (`products`) within a `Datasets.php` file inside a specific feature directory (`tests/Feature/Products`) and then use it in a test file within the same directory. This scopes the dataset's availability to that folder. SOURCE: https://github.com/pestphp/docs/blob/master/datasets.md#_snippet_8 LANGUAGE: php CODE: ``` // tests/Feature/Products/ExampleTest.php... it('has products', function (string $product) { expect($product)->not->toBeEmpty(); })->with('products'); // tests/Feature/Products/Datasets.php... dataset('products', [ 'egg', 'milk' ]); ``` ---------------------------------------- TITLE: Bailing on First Failure with Pest (Bash) DESCRIPTION: Demonstrates using the --bail option to stop the test suite execution immediately upon encountering the first failure or error. SOURCE: https://github.com/pestphp/docs/blob/master/filtering-tests.md#_snippet_1 LANGUAGE: bash CODE: ``` ./vendor/bin/pest --bail ``` ---------------------------------------- TITLE: Pest PHP Expectation: toBeGreaterThanOrEqual() DESCRIPTION: This expectation ensures that the value is greater than or equal to the expected value. SOURCE: https://github.com/pestphp/docs/blob/master/expectations.md#_snippet_11 LANGUAGE: php CODE: ``` expect($count)->toBeGreaterThanOrEqual(21); ``` ---------------------------------------- TITLE: Checking for JSON String with Pest PHP DESCRIPTION: This expectation (`toBeJson`) asserts that the actual string value (`$value`) is a valid JSON formatted string. It attempts to parse the string as JSON. SOURCE: https://github.com/pestphp/docs/blob/master/expectations.md#_snippet_41 LANGUAGE: php CODE: ``` expect('{"hello":"world"}')->toBeJson(); ``` ---------------------------------------- TITLE: Prevent Facades from Being Used with Pest PHP DESCRIPTION: Combining the `not` modifier with `toBeUsed()` allows verifying that specific facades are not utilized anywhere in the application. SOURCE: https://github.com/pestphp/docs/blob/master/arch-testing.md#_snippet_14 LANGUAGE: PHP CODE: ``` arch('facades') ->expect('Illuminate\Support\Facades') ->not->toBeUsed(); ``` ---------------------------------------- TITLE: Using Multi-Argument Datasets in Pest PHP DESCRIPTION: Shows how to provide multiple arguments to a Pest PHP test using an inline dataset containing arrays of values, where each inner array represents a set of arguments for one test run. SOURCE: https://github.com/pestphp/docs/blob/master/datasets.md#_snippet_1 LANGUAGE: php CODE: ``` it('has emails', function (string $name, string $email) { expect($email)->not->toBeEmpty(); })->with([ ['Nuno', 'enunomaduro@gmail.com'], ['Other', 'other@example.com'] ]); ``` ---------------------------------------- TITLE: Expecting Exceptions using Expectation API in Pest PHP DESCRIPTION: Use the `expect()` API with the `toThrow()` method to verify that a given closure throws one or more exceptions. SOURCE: https://github.com/pestphp/docs/blob/master/exceptions.md#_snippet_5 LANGUAGE: php CODE: ``` it('throws exception', function () { expect(fn() => throw new Exception('Something happened.'))->toThrow(Exception::class); }); ``` ---------------------------------------- TITLE: Matching Array Subset with Pest PHP DESCRIPTION: This expectation (`toMatchArray`) verifies that the actual array (`$value`) contains at least the key-value pairs present in the expected subset array (`$array`). It does not require the arrays to be identical, only that the subset matches. SOURCE: https://github.com/pestphp/docs/blob/master/expectations.md#_snippet_20 LANGUAGE: php CODE: ``` $user = [ 'id' => 1, 'name' => 'Nuno', 'email' => 'enunomaduro@gmail.com', 'is_active' => true, ]; expect($user)->toMatchArray([ 'email' => 'enunomaduro@gmail.com', 'name' => 'Nuno' ]); ``` ---------------------------------------- TITLE: Preventing Class Usage with Pest PHP Architecture DESCRIPTION: This snippet illustrates using the `not` modifier with the `toUse` method to prevent files within the `App\Domain` namespace from using any classes from the `Illuminate\Http` namespace. This helps decouple domain logic from framework specifics. SOURCE: https://github.com/pestphp/docs/blob/master/arch-testing.md#_snippet_42 LANGUAGE: php CODE: ``` arch('globals') ->expect('App\Domain') ->not->toUse('Illuminate\Http'); ``` ---------------------------------------- TITLE: Expectation: toBeNull() in Pest PHP DESCRIPTION: This expectation ensures that the provided value is null. It is a straightforward check for null values. SOURCE: https://github.com/pestphp/docs/blob/master/expectations.md#_snippet_43 LANGUAGE: php CODE: ``` expect(null)->toBeNull(); ``` ---------------------------------------- TITLE: Profiling Slow Pest Tests (Bash) DESCRIPTION: Runs the Pest test suite with the --profile option enabled, which collects the duration of each test and provides a report highlighting the slowest tests for optimization. SOURCE: https://github.com/pestphp/docs/blob/master/optimizing-tests.md#_snippet_2 LANGUAGE: bash CODE: ``` ./vendor/bin/pest --profile ``` ---------------------------------------- TITLE: Chipper CI Configuration for Pest PHP DESCRIPTION: This YAML configuration file (`.chipperci.yml`) sets up a Chipper CI pipeline to run Pest PHP tests. It defines the environment (PHP, Node), optional services, triggers the pipeline on push events to any branch, and includes steps for setting up the application, compiling assets, and running the `pest` command. SOURCE: https://github.com/pestphp/docs/blob/master/continuous-integration.md#_snippet_3 LANGUAGE: YAML CODE: ``` version: 1 environment: php: 8.2 node: 16 # Optional services services: # - mysql: 8 # - redis: # Build all commits on: push: branches: .* pipeline: - name: Setup cmd: | cp -v .env.example .env composer install --no-interaction --prefer-dist --optimize-autoloader php artisan key:generate - name: Compile Assets cmd: | npm ci --no-audit npm run build - name: Test cmd: pest ``` ---------------------------------------- TITLE: Default Project Structure with Pest DESCRIPTION: Illustrates the standard directory layout created after installing Pest, highlighting the location of test files (`tests`), configuration files (`TestCase.php`, `Pest.php`), and the PHPUnit configuration (`phpunit.xml`). SOURCE: https://github.com/pestphp/docs/blob/master/writing-tests.md#_snippet_0 LANGUAGE: plain CODE: ``` ├── 📂 tests │ ├── 📂 Unit │ │ └── ExampleTest.php │ └── 📂 Feature │ │ └── ExampleTest.php │ └── TestCase.php │ └── Pest.php ├── phpunit.xml ``` ---------------------------------------- TITLE: Expectation: toHaveLength(int $number) in Pest PHP DESCRIPTION: This expectation ensures that the provided number matches the length of a string value or the number of elements in an iterable value (like an array). SOURCE: https://github.com/pestphp/docs/blob/master/expectations.md#_snippet_46 LANGUAGE: php CODE: ``` expect('Pest')->toHaveLength(4); expect(['Nuno', 'Maduro'])->toHaveLength(2); ``` ---------------------------------------- TITLE: Define Helper Method in Base TestCase (PHP) DESCRIPTION: Presents an alternative approach where helper logic is defined as a protected method `mockPayments` within the base `TestCase` class. This method can then be accessed directly using `$this` within Pest test closures, provided the test case is extended using `pest()->extend()`. SOURCE: https://github.com/pestphp/docs/blob/master/custom-helpers.md#_snippet_2 LANGUAGE: php CODE: ``` use App\Clients\PaymentClient; use PHPUnit\Framework\TestCase as BaseTestCase; use Mockery; // tests/TestCase.php class TestCase extends BaseTestCase { protected function mockPayments(): void { $client = Mockery::mock(PaymentClient::class); // return $client; } } // tests/Pest.php pest()->extend(TestCase::class)->in('Feature'); // tests/Feature/PaymentsTest.php it('may buy a book', function () { $client = $this->mockPayments(); // }) ``` ---------------------------------------- TITLE: Define Test-Specific Teardown Callback (Pest PHP) DESCRIPTION: Chain the `after()` method onto a specific test defined with `it()` or a group defined with `describe` to execute a callback function only after that particular test or group has finished. SOURCE: https://github.com/pestphp/docs/blob/master/pest3-now-available.md#_snippet_20 LANGUAGE: php CODE: ``` it('may list todos', function () { // })->after(function () { // This will run after this test only... }); ``` ---------------------------------------- TITLE: Accessing Failed Requests Count (PHP) DESCRIPTION: Shows how to retrieve the total number of requests that resulted in an error or failure during the stress test from the result object. SOURCE: https://github.com/pestphp/docs/blob/master/stress-testing.md#_snippet_12 LANGUAGE: PHP CODE: ``` $result->requests()->failed()->count(); ``` ---------------------------------------- TITLE: Defining Multiple Test Dependencies in Pest (PHP) DESCRIPTION: Demonstrates how a single test can depend on multiple parent tests. All parent tests must pass, and their return values are available as arguments in the child test function in the order specified in the `depends()` method. SOURCE: https://github.com/pestphp/docs/blob/master/test-dependencies.md#_snippet_4 LANGUAGE: PHP CODE: ``` test('a', function () { expect(true)->toBeTrue(); return 'a'; }); test('b', function () { expect(true)->toBeTrue(); return 'b'; }); test('c', function () { expect(true)->toBeTrue(); return 'c'; }); test('d', function ($testA, $testC, $testB) { var_dump($testA); // a var_dump($testB); // b var_dump($testC); // c })->depends('a', 'b', 'c'); ``` ---------------------------------------- TITLE: Defining Multiple Global Hooks for Specific Group/Folder (Pest PHP) DESCRIPTION: This snippet demonstrates how to define multiple global hooks (beforeAll, beforeEach, afterEach, afterAll) within Pest.php for tests extending TestCase in the 'Feature' directory and 'integration' group. beforeAll and afterAll run once per file, while beforeEach and afterEach run before/after each test within those files. SOURCE: https://github.com/pestphp/docs/blob/master/global-hooks.md#_snippet_2 LANGUAGE: php CODE: ``` pest()->extend(TestCase::class)->beforeAll(function () { // Runs before each file... })->beforeEach(function () { // Runs before each test... })->afterEach(function () { // Runs after each test... })->afterAll(function () { // Runs after each file... })->group('integration')->in('Feature'); ``` ---------------------------------------- TITLE: Checking for String Type with Pest PHP DESCRIPTION: This expectation (`toBeString`) asserts that the actual value (`$value`) is of the string data type. It's a simple type check. SOURCE: https://github.com/pestphp/docs/blob/master/expectations.md#_snippet_40 LANGUAGE: php CODE: ``` expect($string)->toBeString(); ``` ---------------------------------------- TITLE: Conditionally Applying Expectation with when() (PHP) DESCRIPTION: The when() modifier conditionally executes a callback based on a boolean condition. If the condition is true, the provided closure is run, allowing for conditional expectations. This example checks a user's daily limit only if they are verified. SOURCE: https://github.com/pestphp/docs/blob/master/expectations.md#_snippet_84 LANGUAGE: php CODE: ``` expect($user) ->when($user->is_verified === true, fn ($user) => $user->daily_limit->toBeGreaterThan(10)) ->email->not->toBeEmpty(); ``` ---------------------------------------- TITLE: Conditionally Expecting Exceptions with throwsIf in Pest PHP DESCRIPTION: Use the `throwsIf()` method to conditionally verify an exception is thrown only if the provided boolean expression evaluates to true. SOURCE: https://github.com/pestphp/docs/blob/master/exceptions.md#_snippet_3 LANGUAGE: php CODE: ``` it('throws exception', function () { // })->throwsIf(fn() => DB::getDriverName() === 'mysql', Exception::class, 'MySQL is not supported.'); ``` ---------------------------------------- TITLE: Customizing Concurrent Requests (PHP) DESCRIPTION: Demonstrates how to set the number of concurrent requests for the stress test using the `concurrently()` method, often combined with duration customization. SOURCE: https://github.com/pestphp/docs/blob/master/stress-testing.md#_snippet_5 LANGUAGE: PHP CODE: ``` $result = stress('example.com')->concurrently(requests: 2)->for(5)->seconds(); ``` ---------------------------------------- TITLE: Expectation: toHaveKey(string $key) in Pest PHP DESCRIPTION: This expectation ensures that the provided value (typically an array or object) contains the specified key. It can also optionally check if the value associated with the key matches a specific value. Dot notation can be used for nested keys. SOURCE: https://github.com/pestphp/docs/blob/master/expectations.md#_snippet_44 LANGUAGE: php CODE: ``` expect(['name' => 'Nuno', 'surname' => 'Maduro'])->toHaveKey('name'); expect(['name' => 'Nuno', 'surname' => 'Maduro'])->toHaveKey('name', 'Nuno'); expect(['user' => ['name' => 'Nuno', 'surname' => 'Maduro']])->toHaveKey('user.name'); expect(['user' => ['name' => 'Nuno', 'surname' => 'Maduro']])->toHaveKey('user.name', 'Nuno'); ``` ---------------------------------------- TITLE: Prevent Global Functions from Being Used with Pest PHP DESCRIPTION: Combining the `not` modifier with `toBeUsed()` allows verifying that specific global functions are not utilized anywhere in the application. SOURCE: https://github.com/pestphp/docs/blob/master/arch-testing.md#_snippet_13 LANGUAGE: PHP CODE: ``` arch('globals') ->expect(['dd', 'dump']) ->not->toBeUsed(); ``` ---------------------------------------- TITLE: Accessing Base Test Case Methods in Pest PHP DESCRIPTION: This set of snippets shows how to define a custom base test case class (`TestCase`) with a public method (`performThis`) and then access that method from within a Pest test closure after extending the base class for the 'Feature' directory in `tests/Pest.php`. SOURCE: https://github.com/pestphp/docs/blob/master/configuring-tests.md#_snippet_4 LANGUAGE: PHP CODE: ``` use PHPUnit\Framework\TestCase as BaseTestCase; // tests/TestCase.php class TestCase extends BaseTestCase { public function performThis(): void { // } } // tests/Pest.php pest()->extend(TestCase::class)->in('Feature'); // tests/Feature/ExampleTest.php it('has home', function () { $this->performThis(); }); ``` ---------------------------------------- TITLE: Using Glob Patterns with in() for Base Test Case in Pest PHP DESCRIPTION: This snippet illustrates how to use a glob pattern (`Feature/*Job*.php`) with the `in()` method in `tests/Pest.php` to apply a specific base test case (`Tests\TestCase`) only to test files matching the pattern within the 'Feature' directory. SOURCE: https://github.com/pestphp/docs/blob/master/configuring-tests.md#_snippet_2 LANGUAGE: PHP CODE: ``` // tests/Pest.php pest()->extend(Tests\TestCase::class)->in('Feature/*Job*.php'); // This will apply the Tests\TestCase to all test files in the "Feature" directory that contains "Job" in their filename. ``` ---------------------------------------- TITLE: Basic Method Mocking with shouldReceive DESCRIPTION: This PHP snippet demonstrates how to create a mock object using `Mockery::mock()` and set an expectation that a specific method (`post`) should be called on it using `shouldReceive()`. It also shows how to set expectations for multiple methods. SOURCE: https://github.com/pestphp/docs/blob/master/mocking.md#_snippet_1 LANGUAGE: php CODE: ``` use App\Repositories\BookRepository; use Mockery; it('may buy a book', function () { $client = Mockery::mock(PaymentClient::class); $client->shouldReceive('post'); $books = new BookRepository($client); $books->buy(); // The API is not actually invoked since `$client->post()` has been mocked... }); ``` LANGUAGE: php CODE: ``` $client->shouldReceive('post'); $client->shouldReceive('delete'); ``` ---------------------------------------- TITLE: Pest PHP Expectation: toBeFalsy() DESCRIPTION: This expectation ensures that the value is falsy, meaning it evaluates to false in a boolean context. SOURCE: https://github.com/pestphp/docs/blob/master/expectations.md#_snippet_9 LANGUAGE: php CODE: ``` expect(0)->toBeFalsy(); expect('')->toBeFalsy(); ``` ---------------------------------------- TITLE: Pest PHP Expectation: toBeTruthy() DESCRIPTION: This expectation ensures that the value is truthy, meaning it evaluates to true in a boolean context. SOURCE: https://github.com/pestphp/docs/blob/master/expectations.md#_snippet_7 LANGUAGE: php CODE: ``` expect(1)->toBeTruthy(); expect('1')->toBeTruthy(); ``` ---------------------------------------- TITLE: Using Bound Datasets with Models in Pest PHP DESCRIPTION: Demonstrates the use of Pest PHP's bound datasets with closures that create models. This is particularly useful for scenarios where datasets depend on setup performed in `beforeEach`, such as database seeding or model creation. SOURCE: https://github.com/pestphp/docs/blob/master/datasets.md#_snippet_5 LANGUAGE: php CODE: ``` it('can generate the full name of a user', function (User $user) { expect($user->full_name)->toBe("{$user->first_name} {$user->last_name}"); })->with([ fn() => User::factory()->create(['first_name' => 'Nuno', 'last_name' => 'Maduro']), fn() => User::factory()->create(['first_name' => 'Luke', 'last_name' => 'Downing']), fn() => User::factory()->create(['first_name' => 'Freek', 'last_name' => 'Van Der Herten']), ]); ``` ---------------------------------------- TITLE: Output XML Coverage Report (Shell) DESCRIPTION: Writes the code coverage report in XML format to the specified directory. SOURCE: https://github.com/pestphp/docs/blob/master/cli-api-reference.md#_snippet_10 LANGUAGE: Shell CODE: ``` --coverage-xml ``` ---------------------------------------- TITLE: Running Specific Groups with Pest (Bash) DESCRIPTION: Provides an example of using the --group option to run tests that belong to one or more specified groups, such as 'integration' or 'browser'. SOURCE: https://github.com/pestphp/docs/blob/master/filtering-tests.md#_snippet_4 LANGUAGE: bash CODE: ``` ./vendor/bin/pest --group=integration,browser ``` ---------------------------------------- TITLE: Limiting Class Usage with Pest PHP Architecture DESCRIPTION: This snippet demonstrates how to use the `toOnlyBeUsedIn` method to restrict the usage of classes within a specific namespace (`App\Models`) so they can only be used by classes in another specified namespace (`App\Repositories`). This helps enforce architectural layers. SOURCE: https://github.com/pestphp/docs/blob/master/arch-testing.md#_snippet_40 LANGUAGE: php CODE: ``` arch('models') ->expect('App\Models') ->toOnlyBeUsedIn('App\Repositories'); ``` ---------------------------------------- TITLE: Configure Pest Tests in GitHub Actions (YAML) DESCRIPTION: This YAML configuration defines a GitHub Actions workflow (`tests.yml`) that runs Pest tests. It checks out the code, sets up PHP 8.2 with Composer v2 and Xdebug, installs Composer dependencies, and executes the Pest test suite using `./vendor/bin/pest --ci`. SOURCE: https://github.com/pestphp/docs/blob/master/continuous-integration.md#_snippet_0 LANGUAGE: YAML CODE: ``` name: Tests on: ['push', 'pull_request'] jobs: ci: runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v3 - name: Setup PHP uses: shivammathur/setup-php@v2 with: php-version: 8.2 tools: composer:v2 coverage: xdebug - name: Install Dependencies run: composer install --no-interaction --prefer-dist --optimize-autoloader - name: Tests run: ./vendor/bin/pest --ci ``` ---------------------------------------- TITLE: Checking for Array Type with Pest PHP DESCRIPTION: This expectation (`toBeArray`) asserts that the actual value (`$value`) is of the array data type. It's a simple type check. SOURCE: https://github.com/pestphp/docs/blob/master/expectations.md#_snippet_28 LANGUAGE: php CODE: ``` expect(['Pest','PHP','Laravel'])->toBeArray(); ``` ---------------------------------------- TITLE: Conditionally Expecting Exceptions with throwsUnless in Pest PHP DESCRIPTION: Use the `throwsUnless()` method to conditionally verify an exception is thrown only if the provided boolean expression evaluates to false. SOURCE: https://github.com/pestphp/docs/blob/master/exceptions.md#_snippet_4 LANGUAGE: php CODE: ``` it('throws exception', function () { // })->throwsUnless(fn() => DB::getDriverName() === 'mysql', Exception::class, 'Only MySQL is supported.'); ``` ---------------------------------------- TITLE: Initializing Properties with beforeEach() in Pest (PHP) DESCRIPTION: Illustrates how `beforeEach()` can be used to initialize properties (like `$userRepository`) that will be shared and available across all tests within the current file via the `$this` variable, ensuring they are ready before each test runs. SOURCE: https://github.com/pestphp/docs/blob/master/hooks.md#_snippet_2 LANGUAGE: php CODE: ``` beforeEach(function () { $this->userRepository = new UserRepository(); }); it('may be created', function () { $user = $this->userRepository->create(); expect($user)->toBeInstanceOf(User::class); }); ``` ---------------------------------------- TITLE: Decode JSON With Json Modifier Pest PHP PHP DESCRIPTION: Decodes the expected string value from JSON into a PHP array or object, allowing subsequent assertions on the decoded structure. Takes a JSON string as input. Fails if the input is not valid JSON. SOURCE: https://github.com/pestphp/docs/blob/master/expectations.md#_snippet_77 LANGUAGE: php CODE: ``` expect('{"name":"Nuno","credit":1000.00}') ->json() ->toHaveCount(2) ->name->toBe('Nuno') ->credit->toBeFloat(); expect('not-a-json')->json(); //Fails ``` ---------------------------------------- TITLE: Enforcing Exact Coverage Threshold DESCRIPTION: This Bash command demonstrates how to run tests with coverage and enforce an exact percentage threshold. If the overall coverage does not match the specified value (e.g., 99.3), the test run will fail. SOURCE: https://github.com/pestphp/docs/blob/master/test-coverage.md#_snippet_3 LANGUAGE: Bash CODE: ``` ./vendor/bin/pest --coverage --exactly=99.3 ``` ---------------------------------------- TITLE: Invert Expectation With Not Modifier Pest PHP PHP DESCRIPTION: Inverts the result of the subsequent expectation. If the original expectation would pass, the inverted one fails, and vice versa. Takes no arguments. SOURCE: https://github.com/pestphp/docs/blob/master/expectations.md#_snippet_79 LANGUAGE: php CODE: ``` expect(10)->not->toBeGreaterThan(100); expect(true)->not->toBeFalse(); ``` ---------------------------------------- TITLE: Pest PHP Expectation: toBeLessThan() DESCRIPTION: This expectation ensures that the value is strictly less than the expected value. SOURCE: https://github.com/pestphp/docs/blob/master/expectations.md#_snippet_12 LANGUAGE: php CODE: ``` expect($count)->toBeLessThan(3); ``` ---------------------------------------- TITLE: Default Test Case Binding in Pest PHP DESCRIPTION: This snippet demonstrates that within a Pest test closure, the `$this` variable is by default bound to `PHPUnit\Framework\TestCase`, allowing access to standard PHPUnit assertions. SOURCE: https://github.com/pestphp/docs/blob/master/configuring-tests.md#_snippet_0 LANGUAGE: PHP CODE: ``` it('has home', function () { echo get_class($this); // \PHPUnit\Framework\TestCase $this->assertTrue(true); }); ``` ---------------------------------------- TITLE: Applying Strict Preset (PHP) DESCRIPTION: Applies the predefined 'strict' architecture preset to the project, enforcing rules like strict types and final classes. SOURCE: https://github.com/pestphp/docs/blob/master/arch-testing.md#_snippet_52 LANGUAGE: php CODE: ``` arch()->preset()->strict(); ``` ---------------------------------------- TITLE: Install Mockery with Composer DESCRIPTION: This command uses Composer to add Mockery as a development dependency to your project. Mockery is a popular mocking library recommended for use with Pest PHP. SOURCE: https://github.com/pestphp/docs/blob/master/mocking.md#_snippet_0 LANGUAGE: bash CODE: ``` composer require mockery/mockery --dev ```