Skip to content
Advertisement

BadMethodCallException: Call to undefined method AppModelsUser::getFirstMedia()

I am trying to do:

$this->assertFileExists($user->getFirstMedia()->getPath()); In my test. But when I run it I get this error:

BadMethodCallException: Call to undefined method AppModelsUser::getFirstMedia().

I do:

use SpatieMediaLibraryHasMedia;
use SpatieMediaLibraryInteractsWithMedia;

And I also do:

class AssortmentTest extends TestCase implements hasMedia
{
    use RefreshDatabase;
    use InteractsWithMedia;

As far as I know I am using the right traits. What am I doing wrong here?

EDIT:

My test:

public function testUserCanUploadFile()
    {
        $this->withoutExceptionHandling();
        $user = $this->signIn();

        Storage::fake('public'); //Mock a disk
        $file = UploadedFile::fake()->image('test.jpg'); //Upload a fake image.

        $assortmentAttributes = Assortment::factory()->raw(); // Use the assortment factory.
        $assortmentAttributes['image_path'] = $file; // Add a additional field in the assortment factory.

        $this->post(route('assortments.store'), $assortmentAttributes)->assertRedirect(); // Post the fields to the assortmentcontroller store method.
        //Storage::disk('public')->assertExists($file->hashName()); // Check if the field exists.

        $this->assertFileExists($user->getFirstMedia()->getPath());
    }

My store method controller code:

if ($request->hasFile('image')) {
            $image = $request->file('image'); //request the file
            $fileName = md5_file($image . microtime()) . '.' . $image->getClientOriginalExtension(); //use md5 for security reasons and get the extension.
            $image->storeAs('', $fileName, 'public'); //store the file in the public folder disk.
        } 
        
         if ($request->wantsJson()) {
             return response([], 204);
        }

Advertisement

Answer

You are implementing your traits in a TestCase, that is not correct. If you are accessing your users media, you should implement the traits on the User.php model class, its either located in app/User.php or app/Models/User.php.

use SpatieMediaLibraryHasMedia;
use SpatieMediaLibraryInteractsWithMedia;

class User extends Authenticatable implements HasMedia {
   use InteractsWithMedia;
}
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement