[11.x] add ability to disable relationships in factories #53450
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
sometimes when
make
ing orcreate
ing a model, we don't actually care about the relationships. this new property and method allow us to turn them all off at once. when disabled, any attribute that is assigned a factory will instead returnnull
.imagine an
Organization
andUser
models. theorganizations
table is:and the
users
table is:When we define the
UserFactory
we setup the relationship with a factory:This is great for when we seed and when we run feature tests, because it will automatically create the
Organization
s for us.However, this is not always desired, often when you're writing Unit tests. Imagine my user model has an
isAdult()
function:To write a Unit test for this I would
make
a User:Unfortunately, this would try storing Organizations in a database, even though we don't care about that. It would also fail if you didn't have
RefreshDatabase
or something similar on your test.With this PR, you could easily disable all relationships defined in your factories and make this test work: