handkock
handkock

Reputation: 1077

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!

Upvotes: 6

Views: 7681

Answers (3)

mare96
mare96

Reputation: 3859

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.

Upvotes: 10

Tohid Dadashnezhad
Tohid Dadashnezhad

Reputation: 1938

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>

Upvotes: 3

KevDev
KevDev

Reputation: 593

you need to set a different environment for your testing. please look at this. https://laravel.com/docs/5.8/testing#environment and when you test your code the testing will be done on the test environment

and I guess you need a migration to run your old database fields.

Upvotes: 0

Related Questions