Factory not persisting when testing
I'm facing an issue when I'm testing. Sometimes my factory persist the data, but sometimes don't. I'm using Laravel 10. I'm using RefreshDatabase.
This is my setup method
protected function setUp(): void
{
parent::setUp();
$this->user = CreateItems::al(); //this creates permissions tables
$this->actingAs($this->user, 'api')->withoutMiddleware([VerifyCsrfToken::class, VerifyIfUserIsInactivated::class, EnsureEmailIsVerified::class]);
}
and this is my delete_schedule test method
public function test_can_delete_schedule(): void
{
$clients = Client::factory()->create();
$first_client = $clients->first();
$services = Service::factory(5)->create();
$first_service_id = $services->first()->id;
Client_Price::create(['client_id' => $first_client->id, 'client_price_id' => $first_service_id, 'service_price' => 15000]);
$this->user->givePermissionTo('manager_api');
$response = $this->create_schedule($first_client, $services);
dd($response->json());
$schedule = $response->json('new_schedule')['schedule'];
$response = $this->delete(route('destroy', $schedule['id']));
$response->assertStatus(200);
}
and this make a post request
public function create_schedule($client, $services)
{
return $this->postJSON(route('my_address', ['client' => $client->id]), $this->schedule_data($services));
}
If I do a dd($clients) on the test method, I get the data, but if I do Client::all(), I got nothing. However, sometimes the client factory works and persist data I don't know why. The problem is on not persisting clients on db. I tried to put DB::transaction(), but didn't work. If I run the test many times, maybe one time it creates the client.
This behavior causes error when I try to create a schedule, because the clients table is empty.
If someone can help, I'll really appreciate. Thank you.
Please or to participate in this conversation.