Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reset the records in the database in Laravel during testing, but not the database itself

I am tesing now my Laravel app and facing the next problem: my project was migrated from a no-framework PHP project, which already has its own database, so I do no have migrations for most of db data. During the testing I need to refresh my database, but as far as I now, when I use use RefreshDatabase; my whole database is being refreshed(so the tables are being dropped as well), so laravel supposes, that I am migrating my db tables every time, what I am not doing. So the question is: is it possible for every new test to refresh just the records( I mean delete them), but not the whole database ? I've googled it and unfortunately did not find something, which might help. Thanks in advance!

like image 521
handkock Avatar asked Dec 22 '22 21:12

handkock


2 Answers

If you are using Phpunit you can use DatabaseTransactions it will add to the database what you added in tests and after that, it will delete it. Just use it like a trait.

If you don't want to create a testing database it's easy way like this:

<?php

use Illuminate\Foundation\Testing\DatabaseTransactions;

class ExampleTest extends TestCase
{
    use DatabaseTransactions;
    ...

You can find more about that in the docs.

like image 60
mare96 Avatar answered Mar 02 '23 00:03

mare96


You have to set your testing DB on memory so it will not affect your main database for every test. Just change the phpunit.xml file like below:

  <php>
    <env name="APP_ENV" value="testing"/>
    <env name="BCRYPT_ROUNDS" value="4"/>
    <env name="DB_CONNECTION" value="sqlite"/>
    <env name="DB_DATABASE" value=":memory:"/>
    <env name="CACHE_DRIVER" value="array"/>
    <env name="SESSION_DRIVER" value="array"/>
    <env name="QUEUE_DRIVER" value="sync"/>
    <env name="MAIL_DRIVER" value="array"/>
 </php>
like image 26
Tohid Dadashnezhad Avatar answered Mar 02 '23 00:03

Tohid Dadashnezhad