Ad

Laravel Unit Test Fails With Custom Attributes

- 1 answer

I'm trying to write a unit test on my user model that tests if the soft deleted record is still present in the database.

/**
     * check if users are soft deleted only
     *
     * @return void
     */
    public function testUserIsSoftDeleted()
    {
        $user = factory(User::class)->create();

        $user->delete();

        $this->assertSoftDeleted('users', $user->toArray());
    }

This test runs fine until I add a custom attribute to the model.

<?php

namespace App;

use Laravel\Passport\HasApiTokens;
use Spatie\Permission\Traits\HasRoles;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use OwenIt\Auditing\Contracts\Auditable;

class User extends Authenticatable implements MustVerifyEmail, Auditable
{
    use HasApiTokens, Notifiable, SoftDeletes, HasRoles, \OwenIt\Auditing\Auditable;

    protected $guard_name = 'web';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'email', 'password', 'active', 'activation_token', 'email_verified_at'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token', 'activation_token'
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    /**
     * The attributes that should be added to the JSON response
     *
     * @var array
     */
    protected $appends = ['md5_email'];

    /**
     * Convert email address into md5 string
     *
     * @var string
     */
    public function getMd5EmailAttribute()
    {
        return md5(strtolower(trim($this->email)));
    }
} 

When I run the test I get the following error.

enter image description here

How do I include custom attributes in the Found array?

Ad

Answer

To skip md5_email from the query, assign the toArray result to an array and unset the md5_email

Something like

public function testUserIsSoftDeleted()
{
    $user = factory(User::class)->create();

    $user->delete();
    $userInfoArray = $user->toArray()
    // This should skip md5_email getting added to the query
    unset($userInfoArray["md5_email"])

    $this->assertSoftDeleted('users', $userInfoArray);
}
Ad
source: stackoverflow.com
Ad