11 months ago

How to unit test eloquent scopes?

Posted 11 months ago by morteza

I want to unit test to see if specific scope will be called if i call repository method but i don't know how can i do this. Let say i have a Mobile model:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Mobile extends Model
    protected $casts = [
        'verified_at' => 'datetime',

    public function user()
        return $this->belongsTo(User::class);

    public function scopeNumberIs($query, $number)
        return $query->where('number', $number);

And i have a MobileRepository for it:

namespace App\Repositories;

use App\Contracts\MobileInterface;
use App\Contracts\UserInterface;
use App\Mobile;
use App\User;

class MobileRepository extends Repository implements MobileInterface
    public function __construct(Mobile $mobileModel)

    public function getRelatedUserByNumber(string $number): UserInterface
        $user = optional($this->model->numberIs($number)->first())->user;

        if (is_null($user)) {
            $user = new User;

        return new UserRepository($user);

Now i want to make a test to see is scopeNumberIs will be fired when i call getRelatedUserByNumber. I mocked Mobile model but it's calling some other methods that i don't know how to handle them! should i mock them too or there is an easier way. How you do this?

Please sign in or create an account to participate in this conversation.