Test update method Hello Devs,
I'm just trying to be familiar with testing in Laravel, so I have a function to update data here is:
public function isPublished(Request $request, $id)
{
$changeStatus = Post::FindOrFail($id);
if ($changeStatus->status == 1) {
$changeStatus->status = 0;
} else {
$changeStatus->status = 1;
}
// dd($changeStatus);
$changeStatus->save();
return redirect('backend/home')->with('status', 'Post ' . $changeStatus->title . ' Status updated!');
//return response()->json(['success'=>'Status change successfully.']);
}
I tried this test function so far:
public function test_if_status_updated() {
$post = PostFactory::new()->create();
$response = $this->put('/backend/update-status/' . $post->id);
$response->assertOk(200);
}
Can any one help here? and give me resource to be good at testing if possible?
Thanks,
It would help to have a factory state that sets a known Post status first to assert that it was toggled. The 200 status is not correct for a redirect; you can assert against a 3xx status; or the URL:
$post = PostFactory::new()->create(['status' => false]);
$response = $this->put('/backend/update-status/' . $post->id);
$response->assertRedirect('/backend/home');
$this->assertTrue($post->fresh()->status);
$post = PostFactory::new()->create(['status' => true]);
$response = $this->put('/backend/update-status/' . $post->id);
$response->assertStatus(302);
$this->assertFalse($post->fresh()->status);
You also can assert that the Session has the status message.
@tykus First thanks for your reply, the database has been freeshed after using fresh() method but still got: Failed asserting that 1 is false.
@MohcinBN try casting it (or even better add a cast in the model)
$this->assertFalse(!! $post->fresh()->status);
@Sinnbeck Passed! Thanks with the change status passed in create factory to false $post = PostFactory::new()->create(['status' => false]);
@MohcinBN is that assertion correct for this scenario; your expectation should be that the status has changed after taking the action???
If you set up the world where the status is true, then, after taking the action of visiting the URL, the new status should be false
Please sign in or create an account to participate in this conversation.