Last active
February 12, 2020 20:51
-
-
Save jrseliga/bf93d13bfb3fd3f7f2a6830f8cd2de94 to your computer and use it in GitHub Desktop.
Complex factories
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Traditional factory | |
$factory->state(Order::class, function () { | |
return [ | |
'user_id' => function () { | |
return factory(User::class)->create()->id; | |
} | |
]; | |
}); | |
// Simple factory relationship state | |
$factory->state(Order::class, 'with:property', [])->afterCreatingState(Order::class, 'with:property', function ($order) { | |
factory(Property::class)->create([ | |
'order_id' => $order->id, | |
]); | |
}); | |
// Nested relationship state | |
$factory->state(Order::class, 'property:with:loan', [])->afterCreatingState(Order::class, 'property:with:loan', function ($order) { | |
throw_unless($order->property, 'The "with:property" state is required before "property:with:loan" can be used.'); | |
factory(Loan::class)->create([ | |
'property_id' => $order->property->id, | |
]); | |
}); | |
/** | |
* Example usage in test | |
*/ | |
public function testUserNotifiedWhenLoanHasBeenApproved | |
{ | |
Notification::fake(); | |
$order = factory(Order::class)->states('with:property', 'property:with:loan')->create(); | |
$order->property->loan->approve(); | |
Notification::assertSentTo([$order->user], LoanApproved::class); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment