Test Driven Development

If your goal is to be a professional, you should work like PROs do. This is where TDD is a must.

So, first, you create a new Laravel.

Now git add .

Next git commit -m 'initial commit'

If you're doing it really the first time, you'll be asked to provide user email and user name from GitHub.

You can go to your GitHub and follow instructions there by clicking on the New Repository.

Now, you can start on coding through testing and for sure not start coding of a visual side of your project. When you work with a group of people, there's usually a team responsible for that and your focus should only be on code itself.

Now it's time to set up your DB. After that, we can set up our phpunit.xml file with two additional fields:

<server name="DB_CONNECTION" value="mysql"/>
<server name="DB_DATABASE" value=":memory:"/>

like here:


To make this tutorial, I'm using as well video with a tutorial made by Coder's Tape. This way I won't make any mistakes for sure :). I'm only using Laravel 7 and might have few glitches on the way.

In this tutorial, we will try to create software for the Library to manage it.

So, now, when everything is clear, we can move on with coding. Let's Start! :)



So, what's the most common/related thing when it comes to the Library we have in our minds?

A book, right?

In this case, we can start from assigning the name of our file ExampleTest.php which is in the Feature folder which is in the test folder. We can use a name for this file BookReservationTest.php

Now, how works TDD? It works that you write code that never exists. Now you write the code and let the test drive the development.

So, let's start with changing the file which now has a new name. First, we change the class name to match the name. Next, we change the name of the function to match what we do. In our example, we're using public function a_book_can_be_add_to_the_library()
{
}

Now, let say we've hit the endpoint, let's call it books. Then we will expect to have that book in the database. So, this assert that the count of books is 1.Than,  here is our function:


public function a_book_can_be_add_to_the_library()
{
$response = $this->post('/books', [
'title' => 'Cool Book Title',
'author' => 'Piotr'
]);

$response->assertOk();
$this->assertCount(1, Book::all());
}


Now it is time to install PHP unit if you don't have it yet. Once this one is done, we can run a command with a name of our function we've just created:

phpunit --filter a_book_can_be_add_to_the_library

If you have a 404 error, it's mean not found and you should check for typo type of error. This would be not a proper error, this would be the result.

You can add above $response in the function, this line:

$this->withoutExceptionHandling();

Now error should be OK.

I've stopped doing this tutorial on this video at 10:28 seconds:

https://www.youtube.com/watch?v=0Rjsuw1ScXg&t=514s






















No comments:

Post a Comment