How to do the unit test in the Validator class in an Laravel form?

Asked

Viewed 159 times

0

A good day gentlemen.

I am a programming student, at this time I am studying how to perform unit tests using the Laravel 5.3

In my tests I came across the following problem:

My small system only aims to register products in a database. After entering the data in the Formularies send to my function store of my control where I do my validations:

public function store(Request $request)
{
    $this->validate($request, [
        'nome' => 'bail|required|unique:produtos|min:2',
        'valor' => 'bail|required|min:0.1|numeric|'
    ]);
    Produto::create($request->all());
    return redirect('produtos');
}

I would like to do tests that capture whether these validates are actually working, but I am not able to perform such a procedure.

Follow the code:

class ProdutoTest extends TestCase
{

use DatabaseTransactions;
public function testExample()
{

    $this->visit('produtos/create')
         ->type("a", 'nome')
         ->type(15, 'valor')
         ->press('Cadastrar')
         ->seePageIs('produtos/create');



    Produto::create([
        'nome' => '45',
        'valor' => '77'
    ])  ;
}

}

From what I could understand in this test I’m just testing my form, and creating data directly in the database.

How do I test my validates ?

PS:"The names and organization of the test code are quite clueless, since I have not yet set haha..."

1 answer

0

People searching on the internet I believe I have found a satisfying solution

Follows the Code:

public function testNomeComUmCaracter()
{

    $this->visit('produtos/create')
         ->type('h', 'nome')
         ->type(15, 'valor')
         ->press('Cadastrar')
         ->notSeeInDatabase('produtos', ['nome' => 'h'])
         ->seePageIs('produtos/create');
}

In this test I simulated an attempt to register putting a name with only 1 character, in our example "h", such insertion will meet my validates:

public function store(Request $request)
{
$this->validate($request, [
    'nome' => 'bail|required|unique:produtos|min:2',
    'valor' => 'bail|required|min:0.1|numeric|'
]);
Produto::create($request->all());
return redirect('produtos');
}

Then I use the command:notSeeInDatabase With this I’m trying to visualize if the data is not contained in my BD, which means that my validates killed the attempt of Insert

Finally I use the command:use DatabaseTransactions What will make my bank not really populated, since the test shoots the database for the test, and later performs a Rollback, leaving no traces so little spending my Ids.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.