4

Hi I'm trying to create a test for a laravel controller not dependent on the view. I have the following method in my controller class:

public function store(Request $request)
{
    $this->validate($request,[
            'name'=>'required',
            'login'=>'required',
            'password'=>'required'
        ]);
    //TODO: Store to database
    return redirect('usuario/nuevo');
}

And I found the following code to test whether the request had any errors:

public function testStore()
{
    $response=$this->call('GET','usuario.store');
    $this->assertSessionHasErrors();
}

As it is this test should pass since I'm sending a request without the required field filled out however PhpUnit returns the following message:

Session missing key: errors
Failed asserting that false is true.

The only way I can make it work is to try to "see" the error message on the response page by making the test like:

public function testStore()
{
    $this->visit('/usuario/nuevo')
        ->press('Crear')
        ->see('Whoops');
}

This doesn't work for me for two reasons: 1)The test depends on the view to "press" the button and send the request(I wish to test this in a different test and keep this one strictly for the controller) and 2)The test depends on the 'Whoops' string to be present which is obviously bad practice.

I have found several answers claiming that the fist test code should work, but it simply doesn't.

0

2 Answers 2

2

Try it with session start and send empty parameters

       $this->startSession();
       $this->call('GET','usuario.store', array(
        'name' => '',
        'login' => '',
        'password' => ''
    ));
    $errors = session('errors');
    $this->assertSessionHasErrors();
    $this->assertEquals($errors->get('name')[0],""your custom error message);// only for checking exact message
Sign up to request clarification or add additional context in comments.

Comments

0

Your problem is you are not testing what you think you are testing.

To execute the controller's store() you should use a POST method and not GET unless your routes are really weird.

1 Comment

Oh yes, I see that now, however I've changed the request call to POST and still get the same result, my routes are setup with Laravel's resource method like: Route::resource('usuario','Usuarios\UsuariosController');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.