Hello i m testing in laravel 5.5 an api using Mysql as database and DatabaseTransactions.
Suppose that i have a model Team
which may be active
or inactive
and i want to test getting an inactive Team.
$team = Team::inactive()->inRandomOrder()->first(); $response = $this->json('GET',route('teams.show',$team->id); $reponse ->assertStatus(404);
This piece of code is problematic if there is no inactive team in my fake seeded database. So what’s the best approach here ?
1)Should i make sure i seed database with an inactive team ?
2) Should i make an assertion after first line and if $team==null
i make team inactive
for the purpose of testing .
3)Use factory during tests and create fake data ?
The only reason i avoided 3 for the time being is that in more complex relationships with foreign keys i have to seed 3-4 tables.
Advertisement
Answer
You should test each case independently if they can realistically happen. If a case can occur where no inactive teams exist, test for that. If no tears can exist at all, write a test for that too.
Running migrations and seeding is quite common before tests. Laravel provides some helpful utilities to do just that as well as roll back during tear down. Keep your tests atomic and isolated from one another as much as possible.