testing error in laravel.. test code
public function test_only_the_owner_of_a_project_may_update_a_task()
{
// $this->withoutExceptionHandling();
$this->signIn();
$project = Project::factory()->create();
$task = $project->addTask('test tasks');
$this->post($project->path() .'/tasks/' . $task->id, ['body' => 'changed'])->assertStatus(403);
$this->assertDatabaseMissing('tasks', ['body'=> 'changed' ]);
}
error
1) Tests\Feature\ProjectTasksTest::test_only_the_owner_of_a_project_may_update_a_task
Failed asserting that a row in the table [tasks] does not match the attributes {
"body": "changed"
}.
Found similar results: [
{
"body": "changed"
},
{
"body": "changed"
}
].
Are you sure your database is reset after each test?
Check your Project factory, you need to pass the signed in user id to make the project belong to the created user.
@Tray2 here it is , but it does not solve the issue
'owner_id' => function () {
return User::factory()->create()->id;
@Shivamyadav remove that owner_id
And pass it in your test instead.
$this->signIn();
$project = Project::factory()->create( [
'owner_id' => Auth:user()->id
]);
@tray2 the test is to prove the only the owner can change the Task; so it should not belong to the authenticated user.
@shivamyadav it is worth being explicit in your test - set up the world explicitly rather than implicitly, e.g.
public function test_only_the_owner_of_a_project_may_update_a_task()
{
$user1 = User::factory()->create();
$user2 = User::factory()->create();
$project = Project::factory()->create(['owner_id' => $user1->id]);
$task = $project->addTask('test tasks');
$this->actingAs($user2)
->post($project->path() .'/tasks/' . $task->id, ['body' => 'changed'])
->assertStatus(403);
$this->assertDatabaseMissing('tasks', ['body'=> 'changed' ]);
}
@tykus Ah, my bad, thought it the other way around. Didn't read properly.
@tykus but i have passed it in the controller method as jeffreyWay sir in this episode https://laracasts.com/series/build-a-laravel-app-with-tdd/episodes/14 video time from 11:30
controller
public function update(Project $project, Task $task)
{
if(auth()->user() != $project->owner)
{
abort(403);
}
$task->update([
'body' => request('body'),
'completed' => request()->has('completed')
]);
return redirect($project->path());
}
@tykus tried your suggested code also sir but getting same error😔
@Shivamyadav why are you making a POST request to an update endpoint? Use put or patch instead:
$this->actingAs($user2)
->patch($project->path() .'/tasks/' . $task->id, ['body' => 'changed'])
->assertStatus(403);
@tykus patch is not working sir , bcz i have used post method simply to update it !
By the way i have solved my issue , thank you sir for you give your precious time ❤️
@Shivamyadav you defined a POST route for an update endpoint?
@tykus yea sir! Everything working fine
Please sign in or create an account to participate in this conversation.