1
votes

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 App\Models\User::getFirstMedia().

I do:

use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;

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);
        }
1
Should it not be implements HasMedia rather than implements hasMedia?Peppermintology
No I tried that already.Parsa_237
"As far as I know I am using the right traits" Can we see them? What's your User model look like?brombeer
@Parsa_237 According to the docs it's implements HasMediabrombeer

1 Answers

3
votes

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 Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;

class User extends Authenticatable implements HasMedia {
   use InteractsWithMedia;
}