1
votes

I am learning PHPUnit with Laravel and is stucked in an error. I have been following TDD with Laravel from Laracasts and I am facing an PHPunit error when I do a get request.

The error am getting is :

ErrorException: Undefined variable: project

C:\xampp\htdocs\birdboardapp\storage\framework\views\06b7a65ce168ffa601dc57bf60713aa232636d2f.php:7

My test case is

  /** @test */
    public function a_user_can_view_a_project()
    {

        $this->withoutExceptionHandling();

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

        $this->get('/projects/' . $project->id)
            ->assertSee($project->title)
            ->assertSee($project->description);
    }

My routes/web.php is as below

 Route::get('/projects/{project}', 'ProjectsController@show');

ProjectsController is

public function show(){

    $project = Project::findOrFail(request('project'));

    return view('projects.show' ,compact($project));
}

and the view (show.blade.php in projects directory) is

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<h1>{{ $project->title }}</h1>
<div>{{ $project->description }}</div>
</body>
</html>

Now when I try to run the test case a_user_can_view_a_project it gives me an error saying "ErrorException: Undefined variable: project"

1

1 Answers

2
votes

In your controller show method, you seem to be calling compact($project), but that's not how compact function works.

compact accepts the variable name, not the variable itself.

See : https://www.php.net/manual/en/function.compact.php

The solution would be :

  1. use compact correctly :
public function show() {
  $project = Project::findOrFail(request('project'));

  return view('projects.show' , compact('project'));
}
  1. don't use compact at all ( recommended ) :
public function show() {
  $project = Project::findOrFail(request('project'));

  return view('projects.show' , [
    'project' => $project
  ]);
}