static::deleting in a boot method is not working in test

Posted 1 year ago by steveperrycreative

This is my test:

/** @test */
public function deleting_a_task_from_a_project_restores_its_credits()
{
    $this->signInAsAdmin();

    $project = factory('App\Project')->create();

    $task = factory('App\Task')->create([
        'project_id' => $project->id,
        'credits_used' => 20
    ]);

    $project->credits = 100;
    $project->save();

    $response = $this->json('DELETE', $task->path());

    $response->assertStatus(204);

    $this->assertTrue($project->credits == 120);
}

My destroy method on the TasksController is:

public function destroy(Task $task)
{
    $project = $task->project;

    $this->authorize('update', $project);

    $task->delete();

    if (request()->wantsJson()) {
        return response([], 204);
    }

    return redirect($project->path());
}

And my boot method on the Task model is:

protected static function boot()
{
    parent::boot();

    static::creating(function ($task) {
        $task->project->removeCredits($task->credits_used);
    });

    static::deleting(function ($task) {
        $task->project->addCredits($task->credits_used);
    });
}

The add and remove credits methods just perform some basic maths and save, nothing fancy. When I test creating a task the credits get removed from the project as expected. However when I run the above delete test nothing happens to the credits on the project, they stay at 100.

The boot method runs fine. I've even tried sliming it by just doing:

static::deleting(function ($task) {
    $task->project->credits = 120;
    $task->project->save();
});

But that doesn't work either. I'm stumped. Am I missing something silly!?

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

Laracasts Mascot

Hi, Have We Met Yet?

Did you know that, in addition to the forum, Laracasts includes well over 1000 lessons on modern web development? All for the price of one lunch out per month.

Sign Me Up

Channels

Reply to

Use Markdown with GitHub-flavored code blocks.