I'm using Laravel 5.6. I added event listeners to a class that call a method on its parent class during the created and deleted event. I'm having trouble writing a test for the deleted event. Something strange is going on.
Here's the model with the listeners:
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Sku extends Model {
use SoftDeletes;
public static function boot()
{
parent::boot();
static::created(function ($sku) {
$sku->product->updateSkuCount();
});
static::deleted(function ($sku) {
$sku->product->updateSkuCount();
});
}
public function product()
{
return $this->belongsTo(Product::class);
}
}
Here's the updateSkuCount method on the Product model:
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Product extends Model {
use SoftDeletes;
public function skus()
{
return $this->hasMany(Sku::class);
}
public function updateSkuCount()
{
$this->sku_count = $this->skus()->count();
$this->save();
}
}
And here is the test I'm trying to make pass:
/**
* @test
*/
public function deleting_a_sku_updates_the_product_sku_count_attribute()
{
$product = factory(Product::class)->create();
$skus = factory(Sku::class, 2)->create([
'product_id' => $product->id
]);
$skus->first()->delete();
$product->refresh();
$this->assertSame(1, $product->sku_count);
}
It seems extremely straight forward to me, but it's not working. The test keeps telling me that $product->sku_count is actually 2. I've been adding output throughout all the methods being called to try and debug, and everything seems to be getting called correctly. Everything indicates that sku_count should be set to 1, but for some reason the instance of $product in the test keeps saying 2.
I have also found that when I comment out the created listener, the test passes. So there seems to be some kind of interaction going on between the two listeners.
I am very confused and can not figure out what's going on. Does anyone have any idea what would be causing this?
Additionally, just to show you that the updateSkuCount method works, here is the test for the created listener, which passes correctly:
/**
* @test
*/
public function creating_skus_updates_the_product_sku_count_attribute()
{
$product = factory(Product::class)->create();
$skus = factory(Sku::class, 2)->create([
'product_id' => $product->id
]);
$product->refresh();
$this->assertSame(2, $product->sku_count);
}
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire