6

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!

handkock
  • 1,067
  • 2
  • 11
  • 23
  • 1
    You can create a `Trait` to `TRUNCATE` all your database table for your testing. For reference, check this answer: https://stackoverflow.com/a/50904595/4369919 – N69S Aug 19 '19 at 10:22

3 Answers3

9

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.

mare96
  • 3,749
  • 1
  • 16
  • 28
  • Thank you, I think that's it. – handkock Aug 19 '19 at 10:29
  • You're welcome, just mark it as answer, thanks. @handkock – mare96 Aug 19 '19 at 10:30
  • One issue with `DatabaseTransactions` is that unit tests might still assume the DB is non-empty or contains specific records which aren't created in migrations but _are_ present in the real, deployed DBs. I'd prefer to stand up a test DB as part of running the tests. – Sarah Messer Feb 24 '23 at 16:51
3

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>
Tohid Dadashnezhad
  • 1,808
  • 1
  • 17
  • 27
  • 2
    For sure you need use separate DB for unit testing. But you need after test reset you tables, as each test is unique. – GrigorAtaryan Nov 26 '21 at 12:32
0

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.

KevDev
  • 541
  • 2
  • 6
  • 20