Factory - try to create #52948
Replies: 2 comments
-
|
Beta Was this translation helpful? Give feedback.
-
I think this is codesmell, you create a record for tests to make sure the user is in the correct state before the test runs. suppose you want to test if a phone number is changed. If you would try create the user and the user exists, the phonenumber might be already changed as well. Someone changes the code, the code no longer updates the phone number, but your test still succeeds. you can circumvent that by either adding a precondition test, or you can truncate the table before you do that. adding a tryToCreate and a precondition test is too much work for just using Model::truncate in your afterEach/teardown hook. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
In Eloquent, when we use a factory to create a new record, it always tries to add it to the database. This can cause an error if a record with the same id already exists. Right now, we have to manually check if the record is there before creating it.
To make this easier, a new
tryToCreate
method could be added. This method would first check if a record with the givenid
is already in the database. If it exists, it wouldn’t create anything. If it doesn’t, it would create the record. This would be useful for tests where we just need to make sure a record with a specificid
exists.Example
When a user with id 1 already exists in the database.
This will throw an QueryException:
This should just try to create.
If a user with
id
1 already exists, nothing happens. If not, a new user with thatid
is created. This will save time by not needing to check for the record manually.Beta Was this translation helpful? Give feedback.
All reactions