Laravel 9: testing get profile (by slug) for created row

Viewed 52

I wrote test:

public function test_hello_world(){
    $test = User::create(['name' => 'Test',
        'email' => 'test@test.com',
        'password' => 'password',
    ]);
    Profile::create([
        'user_id' => $test->id,
        'name' => 'Test',
        'slug' => 'test'
    ]);

    $this->get('/profile/test')
        ->assertStatus(200);
}

What this code should testing? After get to this url it should display details about profile. If profile with this slug doesn't exist, we have error 404. In this test I create user and profile table (this 2 tables is connection) but after run test I have the error:

Expected response status code [200] but received 404. Failed asserting that 200 is identical to 404.

Why I have this error since I created profile with this slug? For me the best option will be create testing database with a lot of records and conduct all test on it. Is it possible? How do that?

@Edit

I have a route and controller's method which display user's profile. If I go (in web browser) to localhost/profile/slug, it works, if this profile exist. My controller's method look like this:

public function show($slug) {
    $profile = Profile::where('slug', $slug)
                      ->firstOrFail();

    return Inertia::render('Profile/Single', [
        'profile' => $profile,
    ]);
}

And route:

Route::get('/profile/{slug}',
           [ProfileController::class, 'show'])
           ->name('profile.show');
1 Answers

According to your requirement you have to create route for getting profile from slug name. You did wrong in single function. Without creating route it will not worked.

So below example may work for you.

For example:-

For creating data

public function createData(){

  $user = User::create(['name' => 'Test',
   'email' => 'test@test.com',
   'password' => 'password',
  ]);

  Profile::create([
    'user_id' => $user->id,
    'name' => 'Test',
    'slug' => 'test'
  ]);

  return redirect()->back()->with('success', 'Data created');
}

For Getting Data

public function getDataBySlug($slug){
   $profile = Profile::where('slug',$slug)->firstOrFail();

   return redirect('/dashboard')->with('slug', $slug);
}

In route file you have to mention table name and column name {profile:slug} instead of id

Route::get('/profile/create', 'Controller@createData');
Route::get('/profile/{profile:slug}', 'Controller@getDataBySlug');

Your route definition is wrong please do as above

Related