pknad505's avatar

Laravel Feature Test but data doesnt appear until after a request

I'm having troubles with feature tests and data seeming to both exist and not exist depending on where and when that data is being retrieved from.

My test only seems to work if I run them one at a time but if run them all together using php artisan test then there seems to be no data so the test fails

This is my class:

<?php


namespace Tests\Feature;

use App\AssetGroup;
use Throwable;
use Illuminate\Foundation\Testing\RefreshDatabase;

class AssetGroupTest extends CoreFeatureTest
{
    use RefreshDatabase;

    public function setUp(): void
    {
        parent::setUp();
        $this->seed();
        $this->logMeIn();
    }
    
        public function testAssetGroupShow(): void
    {
        $response = $this->get('/api/asset-group?keyBy=none');

        $response->assertStatus(200);

    }

    public function testAssetGroupDelete(): void
    {
        $assetGroup = AssetGroup::whereHas('user', function ($query) {
            $query->where('user_id', 1);
        })->first();

        $response = $this->delete('/api/asset-group/' . $assetGroup->uuid);

        $response->assertStatus(200);
        $this->assertSoftDeleted($assetGroup);
    }
}
0 likes
2 replies
tykus's avatar

This looks a little strange to me:

$assetGroup = AssetGroup::whereHas('user', function ($query) {
	$query->where('user_id', 1);
})->first();

what is the relationship between AssetGroup and User; and where is the foreign key user_id?

If I wanted an AssetGroup belonging to the authenticated user, I would go this way (assuming you know that the authenticated user always has id of 1:

$assetGroup = AssetGroup::where('user_id', 1)->first();

Please or to participate in this conversation.