Using Model Factory States To Create Related Models

Laravel’s model factories can be used to automatically create related models when the factory is called. This is a great way to DRY up the arrange portion of your tests but can cause some problems. In this post we will examine how model factory states can be used to avoid any issues.

Persisting Polymorphism

Recently I worked on a project where a user’s choice needed to permanently modify the behavior of an object. The gist of the project is that a user is creating a job posting and at some point they will choose how they wish to publish the job: using a job credit, as a daily rate, on a recruiting plan, etc. The choice of publishable type alters the behavior of the job every time the user decides to change its status (from draft to open, draft to scheduled, open to closed).