MadGenius88
2/23/2017 - 4:11 PM

How Do I: How Do I Unit Test Eloquent Models?

How Do I: How Do I Unit Test Eloquent Models?

<?php

class NotificationTest extends TestCase
{
    /**@test*/
    function it_prepares_a_notifcation()
    {
        $notification = Notification::prepare('a mesaege');
        
        $this->assertEquals('a message. $notification-message);
        $this->assertTrue($notification->mustBeLoggedIn);
        $this->assertFalse($notification->exists)
    }
    
    /**@test*/
    function it_sets_the_url_for_the_notification()
    {
        $notification = Notification::prepare('a mesaege')->to('http://example.com');
        
        $this->assertEquals('http://example.com', $notification->link);
    }
    
    /**@test*/
    function it_scopres_queries_to_those_create_within_the_given_number_of_days()
    {
         // assuming we have a notificaiton that is new
         factory(Notification::class)->create();
         
         // and also a notification that is a week old
         factory(Notification::class)->create([
            'created_at' => carbon::now()->subWeek()
         ]);
         // when I fetch all notification but scope them to these from the last day
         $reults = Notification::latest()->get();
      
         // I should only get one result
         $this->assertCount(1, $results); 
    }
    
}
<?php 

namespace App;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;

class Notification extends Model
{
    protected $fillable = ['message', 'mustBeLoggedIn'];
  
    public static function prepare($message, $mustBeLoggedIn = true)
    {
        return new static(compact('message', 'mustBeLoggedIn'));
    }
}

    public function to($url)
    {
        $this->link = $url;
      
        return $this;
    }

    public function scopeLatest(Builder $query, $daysBack = 1)
    {
        return $query->where('created_at', '>', Carbon::now()->subDays($daysBack))
    }
}
<?php

/*...*/

$factory->define(App\User::class, function (Faker\Generator $faker) {
    return [
        'name' => $faker->name,
        'email' => $faker->safeEmail,
        'password => bcrypt(str_random(10)),
        'remember_token' => str_random(10),
    ];
});

$factory->define(App\Notification::class, function (Faker\Generator $faker) {
    return [
        'message' => $faker->sentence,
        'mustBeLoggedIn' => $faker->boolean(),
        'password => bcrypt(str_random(10)),
        'remember_token' => str_random(10),
    ];
});