Skip to main content

Admin Role and Companies

Premium
6 min read
Ahmad avatar

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.

Kwesi Danquah avatar

the tests failed at my end too so i just removed the constrained from the role_id

Nerijus avatar

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.

Ahmad avatar

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, CONSTRAINT users_role_id_foreign FOREIGN KEY (role_id) REFERENCES roles (id)) (Connection: mysql, SQL: insert into users (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))

Nerijus avatar

My guess is you don't have roles seeded. Constraints should be always used.

jocagutierrezz avatar

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 add public $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

Nerijus avatar

You don't need to add it in every test. Add in the TestCase.php and it will work for every test.

yussuf avatar

This worked for me

jwinder avatar

@jocagutierrezz youre the goat man thanks

Lister avatar

@Ahmad add role_id to your DatabaseSeeder just like this.

$this->call(RoleSeeder::class);

User::factory()->create([ 'role_id' => 1, ]);

Yuri Neves avatar

Need to create a database to run the tests in laravel?

Povilas Korop avatar

Yes it should be either a separate MySQL database, or SQLite database in memory. Watch this lesson from my course about testing for beginners.