phplaraveltestingilluminate-container

Laravel Illuminate Testing method for refreshing DB only at the start


I have a code that runs everyday and deletes some information from the database.
I am trying to test this code using artisan's test functionality and would like to be able to see the final result on phpmyadmin, however if I add Illuminate\Foundation\Testing\RefreshDatabase The DB seems to refresh at the start AND at the end.

Is there a way to refresh the database at the start only?

Here is a shortened sample of my code:

namespace Tests\Feature;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Server\Models\User;
use Server\Models\...; //call multiple models
use Tests\TestCase;

class TestRemoveCertainData extends TestCase
{
    use RefreshDatabase;

    public function removeCertainData()
    {
        //create all necessary data using factory
        factory(User::class)->create(); // etc...
        
        //should run the code that deletes certain data
        $this->artisan('remove_data_command')->assertSuccessful();
    }
}

So after I run php artisan test Tests\Feature\TestRemoveCertainData I would like to check if php artisan remove_data_command worked the way I intended it to on the phpmyadmin panel.


Solution

  • I wasn't able to find a method for it.
    But what I understood was that the idea of keeping the database, and checking it yourself was wrong.

    The Laravel Tests themselves are supposed to be something that someone can run in the future with one simple command, such as php artisan test --group=my_group_name.
    Therefore the correct way to solve this is to add an assert and compare the tables to your expectations.

    namespace Tests\Feature;
    
    use Illuminate\Foundation\Testing\RefreshDatabase;
    use Server\Models\User;
    use Server\Models\...; //call multiple models
    use Tests\TestCase;
    
    class TestRemoveCertainData extends TestCase
    {
        use RefreshDatabase;
    
        public function testRemoveCertainData()
        {
            
            $users = [
                $this->createUserType1(),
                $this->createUserType2(),
                $this->createUserType3(),
                $this->createUserType4(),
            ];
            
            // deletes emails for users of type 2 and 4
            $this->artisan('delete_certain_emails')->assertSuccessful();
    
            // expecting the emails of user 2 and 4 to disappear
            $expected = [
                $users[0]->mail,
                null,
                $users[2]->mail,
                null,
            ];
    
            $result = User::pluck('mail')->toArray();
    
            $this->assertEquals($expected, $result);
        }
    }