Does RefreshDatabase rollback changes after each test of at the end of all

Published 1 week ago by darkec

Let's say I have simple test with 2 functions:

public function testCreateUser()
{
    User::create(['username' => 'test']); 
}

And this is where I create a user and it has id=1.

Now I want to get that user in next test function

public function testGetUser()
{
    User::find(1); 
}

Will this user be in my database or will RefreshDatabase rollback my changes after it finishes with testCreateUser() so my user won't be saved in the database?

Best Answer (As Selected By darkec)
arukomp

Depends.

If you're using an in-memory database (DB_DATABASE = :memory:) then the trait will refresh the database after each test.

If you're using a normal database, then it will migrate ONCE, and then run your tests within transactions. This is faster than migrating and rolling back after each test individually

lerzenit

You can just try and find out, but if I'm not wrong, it does the rollback after each test so testGetUser will fail

joshuafranks

RefreshDatabase resets your database after each test to eliminate the risk of data interference.

You can read more about the RefreshDatabase trait in the documentation.

https://laravel.com/docs/5.6/database-testing

arukomp
arukomp
1 week ago (18,850 XP)

Depends.

If you're using an in-memory database (DB_DATABASE = :memory:) then the trait will refresh the database after each test.

If you're using a normal database, then it will migrate ONCE, and then run your tests within transactions. This is faster than migrating and rolling back after each test individually

Please sign in or create an account to participate in this conversation.