From af205a8dc71bc872b1e3321ea4d1df36df153256 Mon Sep 17 00:00:00 2001 From: Ollie Date: Tue, 27 Oct 2026 22:27:52 +0000 Subject: [PATCH] Make email and password match in UserFactory Small quality of life change to make it easier to log in as users created with this factory (and that don't specify a password to use). Use a closure to set the password so that it works with both the default provided and overridden emails, and add tests to verify this. The test file is located at `tests/Feature/Models/UserFactoryTest.php` with the idea that it will sit next to the model's `UserTest.php` once all models and their tests are moved under a `*\Models` namespace. Given that factories are configured and accessed via its model, having the model and factory tests side-by-side seemed appropriate. Alternative locations considered: * `tests/Database/Factories` to match the namespace of factories * `tests/Feature/Factories` to fit in to Laravel's default test directory structure[1] [1]: https://laravel.com/framework/docs/11.x/testing --- database/factories/UserFactory.php | 3 ++- tests/Feature/Models/UserFactoryTest.php | 32 ++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) create mode 100644 tests/Feature/Models/UserFactoryTest.php diff --git a/database/factories/UserFactory.php b/database/factories/UserFactory.php index b535d4b46..4ba906c2c 100644 --- a/database/factories/UserFactory.php +++ b/database/factories/UserFactory.php @@ -20,8 +20,9 @@ class UserFactory extends Factory { */ public function definition() { return [ - 'password' => $this->faker->password(), 'email' => $this->faker->unique()->safeEmail(), + // use the email as the password so that it is easier to log in as these users + 'password' => fn (array $attributes) => $attributes['email'], 'verified' => $this->faker->boolean(), ]; } diff --git a/tests/Feature/Models/UserFactoryTest.php b/tests/Feature/Models/UserFactoryTest.php new file mode 100644 index 000000000..af1948069 --- /dev/null +++ b/tests/Feature/Models/UserFactoryTest.php @@ -0,0 +1,32 @@ +make(); + + $this->assertTrue(Hash::check($user->email, $user->password)); + } + + public function testDefaultPasswordMatchesOverriddenEmail(): void { + $email = 'factory@example.com'; + $user = User::factory()->make(['email' => $email]); + + $this->assertTrue(Hash::check($email, $user->password)); + } + + public function testExplicitPasswordOverridesDefault(): void { + $password = 'explicit-password'; + $user = User::factory()->make(['password' => $password]); + + $this->assertTrue(Hash::check($password, $user->password)); + $this->assertFalse(Hash::check($user->email, $user->password)); + } +}