diff --git a/user_guide_src/source/changelogs/v4.5.0.rst b/user_guide_src/source/changelogs/v4.5.0.rst index fef00aa02da5..7fe6c94e1723 100644 --- a/user_guide_src/source/changelogs/v4.5.0.rst +++ b/user_guide_src/source/changelogs/v4.5.0.rst @@ -44,6 +44,8 @@ Testing - **CLI:** The new ``InputOutput`` class was added and now you can write tests for commands more easily if you use ``MockInputOutput``. See :ref:`using-mock-input-output`. +- **Fabricator:** The Fabricator class now has the ``setUnique()``, ``setOptional()`` and ``setValid()`` + methods to allow calling of Faker's modifiers on each field before faking their values. - **TestResponse:** TestResponse no longer extends ``PHPUnit\Framework\TestCase`` as it is not a test. Assertions' return types are now natively typed ``void``. diff --git a/user_guide_src/source/testing/fabricator.rst b/user_guide_src/source/testing/fabricator.rst index e2a4e5910ead..1f42402a972d 100644 --- a/user_guide_src/source/testing/fabricator.rst +++ b/user_guide_src/source/testing/fabricator.rst @@ -62,6 +62,27 @@ a child class in your test support folder: .. literalinclude:: fabricator/006.php +Setting Modifiers +================= + +.. versionadded:: 4.5.0 + +Faker provides three special providers, ``unique()``, ``optional()``, and ``valid()``, +to be called before any provider. Fabricator fully supports these modifiers by providing +dedicated methods. + +.. literalinclude:: fabricator/022.php + +The arguments passed after the field name are passed directly to the modifiers as-is. You can refer +to `Faker's documentation on modifiers`_ for details. + +.. _Faker's documentation on modifiers: https://fakerphp.github.io/#modifiers + +Instead of calling each method on Fabricator, you may use Faker's modifiers directly if you are using +the ``fake()`` method on your models. + +.. literalinclude:: fabricator/023.php + Localization ============ diff --git a/user_guide_src/source/testing/fabricator/022.php b/user_guide_src/source/testing/fabricator/022.php new file mode 100644 index 000000000000..dbde0ff3a5f7 --- /dev/null +++ b/user_guide_src/source/testing/fabricator/022.php @@ -0,0 +1,11 @@ +setUnique('email'); // sets generated emails to be always unique +$fabricator->setOptional('group_id'); // sets group id to be optional, with 50% chance to be `null` +$fabricator->setValid('age', static fn (int $age): bool => $age >= 18); // sets age to be 18 and above only + +$users = $fabricator->make(10); diff --git a/user_guide_src/source/testing/fabricator/023.php b/user_guide_src/source/testing/fabricator/023.php new file mode 100644 index 000000000000..2729e60d18a3 --- /dev/null +++ b/user_guide_src/source/testing/fabricator/023.php @@ -0,0 +1,20 @@ + $faker->firstName(), + 'email' => $faker->unique()->email(), + 'group_id' => $faker->optional()->passthrough(mt_rand(1, Fabricator::getCount('groups'))), + ]; + } +}