dimanche 7 février 2021

In Laravel, how can I test a "show" route with a parameter, after having created a model instance?

I've got an Idea model which has:

  • public_id (auto-generated)
  • title
  • slug
  • content

It also has a pretty_slug attribute (which combines the public_id and the slug). This pretty_slug is used in the "show" route URL.

I want to test this "show" route which has a /ideas/{pretty_slug} format.

So I create an Idea instance, and want to use its pretty_slug as a parameter in the ideas.show route:

public function test_guest_can_get_show_page()
{
    $idea = Idea::factory()->create([
        'title' => 'My awesome idea',
        'content' => 'Lorem ipsum this.'
    ]);

    $response = $this->get(route('ideas.show', ['pretty_slug' => $idea->pretty_slug]));
    $response->assertStatus(200);
}

This fails because the status code is 500 for some reason.

I have another similar database test which works:

public function test_models_slug_is_created()
{
    Idea::factory()->create([
        'title' => 'My awesome idea',
        'content' => 'Lorem ipsum this.'
    ]);

    $this->assertDatabaseHas('ideas', [
        'slug' => 'my-awesome-idea',
    ]);
}

Or an "index" route test, which also works:

public function test_guest_can_get_index_page()
{
    $response = $this->get(route('ideas.index'));
    $response->assertStatus(200);
}

I'm not sure how to do this. I haven't found any solution on the internet or the official documentation. Can anyone help me out?

Aucun commentaire:

Enregistrer un commentaire