32
loading...
This website collects cookies to deliver better user experience
Cat
, how many tests do you write?class CatsController extends Controller
{
public function store()
{
request()->validate([
'name' => 'required',
'lives' => 'required|integer'
]);
Cat::create(request(['name', 'lives']));
return back()->with('success', 'Cat created.');
}
}
/** @test */
public function a_user_can_create_a_cat()
{
$this->post('/cats', ['name' => 'Jafar', 'lives' => 9])
->assertStatus(302);
$this->assertDatabaseHas('cats', ['name' => 'Jafar', 'lives' => 9]);
}
Cat
gets stored in the database. /** @test */
public function a_user_cant_create_a_cat_with_invalid_lives()
{
$this->post('/cats', ['name' => 'Jafar', 'lives' => 'One'])
->assertSessionHasErrors('lives')
->assertStatus(302);
$this->assertDatabaseMissing('cats', ['name' => 'Jafar', 'lives' => 'One']);
}
lives
field, they should be redirected back with an error for the lives
field and no new record should be created in the cats
table./**
* @test
* @dataProvider invalidCats
*/
public function a_user_cant_store_an_invalid_cat($invalidData, $invaludFields)
{
$this->post('/cats', $invalidData)
->assertSessionHasErrors($invaludFields)
->assertStatus(302);
$this->assertDatabaseCount('cats', 0);
}
public function invalidCats()
{
return [
[
['name' => 'Jafar', 'lives' => 'One'],
['lives']
],
[
['name' => 'Jafar'],
['lives']
],
[
['lives' => 5],
['name']
]
];
}
invalidCats
contains two elements: invalidCats
combination is tested and, each time, we assert that validation fails exactly for the fields we expect.assertDatabaseCount
call is an extra assertion to ensure nothing was added to the database. Knowing that this test will be running for