Home > Net >  How to write a unit test for model have appends property
How to write a unit test for model have appends property

Time:03-21

I have the model Products, which has the protected property $appends = ['avg_rating']. This avg rating is being set by an getAvgRatingAttribute() function. I want to write a unit test for append property in the model Products, so any ideas?

class Product extends Model
{
    protected $appends = [
        'avg_rating',
    ];
    
    public function getAvgRatingAttribute()
    {
        return $this->comments()->avg('rating');
    }
}

CodePudding user response:

I want to test the model has the appended property and it's returning the correct avg. Do you have any idea?

//use Tests\TestCase;
public function test_your_test_name(){
 $post = Post::create([]);
 $post->comments()->saveMany([
   new Comment(['rating' => 2]),
   new Comment(['rating' => 4]),
   new Comment(['rating' => 1]),
  ]);

 $this->assertTrue(isset($post->avg_rating)); //to test if attribute is set
 $this->assertEquals(  (2 4 1)/3, $post->avg_rating ); //test if avg rating is correct
}

I maybe missing the point, but, I should say that these tests seem unnecessary. This is the same as testing if getAvgRatingAttribute sets the attribute, and if avg function returns the correct average, which, the framework has already tested.

  • Related