diff --git a/testing.md b/testing.md index 8532d5235b..e67e402ec7 100644 --- a/testing.md +++ b/testing.md @@ -2,6 +2,7 @@ - [Introduction](#introduction) - [Environment](#environment) +- [Caching Configuration](#caching-config) - [Creating Tests](#creating-tests) - [Running Tests](#running-tests) - [Running Tests in Parallel](#running-tests-in-parallel) @@ -31,6 +32,62 @@ You are free to define other testing environment configuration values as necessa In addition, you may create a `.env.testing` file in the root of your project. This file will be used instead of the `.env` file when running Pest and PHPUnit tests or executing Artisan commands with the `--env=testing` option. + +## Caching Config + +When running tests, Laravel boots the application for each individual test method. Without a cached configuration file, each config file for your application must be loaded at the start of a test. To build the configuration once and re-use it for all tests in a single run, Laravel offers the `Illuminate\Foundation\Testing\WithCachedConfig` trait. + +```php tab=Pest +use(WithCachedConfig::class); + +test('modifies config', function () { + config(['services.postmark.key' => 'xyz']); + expect(config('services.postmark.key'))->toBe('xyz'); +}); + +test('uses default config', function () { + expect(config('services.postmark.key'))->not->toBe('xyz'); +}); +``` + +```php tab=PHPUnit + 'xyz']); + $this->assertEquals('xyz', config('services.postmark.key')); + } + + /** + * A test that makes no modification to the config. + */ + public function test_uses_default_config(): void + { + $this->assertNotEquals('xyz', config('services.postmark.key')); + } +} +``` + +> [!NOTE] +> Changes to the cache in one test case should not affect the configuration that is loaded in subsequent tests. + ## Creating Tests