Comments & Discussion
YN
Need to create a database to run the tests in laravel?
PK
Yes it should be either a separate MySQL database, or SQLite database in memory. Watch this lesson from my course about testing for beginners.
Hello, The test failed at my end, I had to remove the constrain at the add_role_id_to_users_table, then everything went as expected.
the tests failed at my end too so i just removed the constrained from the role_id
Just reran this test and it's all green for me. Maybe you are missing something. Without some code and error message can't help.
This is the error: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (
testing_reservation_project.users, CONSTRAINTusers_role_id_foreignFOREIGN KEY (role_id) REFERENCESroles(id)) (Connection: mysql, SQL: insert intousers(name,email,email_verified_at,password,remember_token,role_id,updated_at,created_at) values (Emely Greenfelder IV, konopelski.edwin@example.com, 2023-07-08 20:59:46, $2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi, 56Sx9OSLgp, 3, 2023-07-08 20:59:46, 2023-07-08 20:59:46))My guess is you don't have roles seeded. Constraints should be always used.
The problem is that every Test is using
use RefreshDatabase;to refresh tables after testing, in my case by default it´s not seeding at all, just migrating, so I just addpublic $seed = true;in every single test to let know that I want to seed tables as well, this works for me and didn´t have to remove constrained from migration.Solved it in last comment on: https://laracasts.com/discuss/channels/testing/manually-seed-refreshdatabase
You don't need to add it in every test. Add in the
TestCase.phpand it will work for every test.This worked for me
@jocagutierrezz youre the goat man thanks
@Ahmad add role_id to your DatabaseSeeder just like this.
$this->call(RoleSeeder::class);
User::factory()->create([ 'role_id' => 1, ]);