0

I'm testing saving data into the database. When missing required fields I throw an exception and then redirect from my controller:

try {
            $product = Product::create([
                'name' => $request->name,
                'description' => $request->description,
            ]);

            return redirect('home')->with('success', 'Record has been added');

        } catch(\Exception $e) {

            return redirect()->to('course/create')
                    ->withInput($request->input())
                    ->with('errors', 'Required Fields Not Submitted');
        }

I wanna test the redirect, whether the session has errors and whether the initial data passed is returned in order to populate the form, so in my unit test I have:

$response = $this->post("/courses/", $data);

$response->assertRedirect('/courses/create');
$response->assertSessionHasErrors();
//$response->assertSessionHasAll();
$response->assertHasOldInput();

but when hitting assertSessionHasErrors I'm getting:

Error: Call to a member function getBag() on string

and when hitting assertHasOldInput I'm getting:

BadMethodCallException: Call to undefined method Illuminate\Http\RedirectResponse::assertHasOldInput()

what seems to be the issue?

Thanks.

MrCujo
  • 1,218
  • 3
  • 31
  • 56

2 Answers2

0

Do this instead:

$response = $this->call('POST',  "/courses/", $data);

$response->assertRedirect('/courses/create');
$response->assertSessionHasErrors();
$response->assertHasOldInput();
Chukwuemeka Inya
  • 2,575
  • 1
  • 17
  • 23
0

I think you should use call method instead of post

Docs - Calling Routes From Tests

Try this

$response = $this->call("POST", "/courses/", $data);
$response = $this->assertRedirect('/courses/create');
$response = $this->assertSessionHasErrors();
$response = $this->assertHasOldInput();
Marat Badykov
  • 824
  • 4
  • 8