Reputation: 2639
I'm trying to test my Laravel system using the DatabaseTransactions trait. The problem is that it rollback the transaction only after all tests on a TestCase were ran. Is it possible to have a fresh database instance for every test in a TestCase?
This test case sometimes return all green but sometimes not. When it executes the test as they are wrote everything goes OK but when the order is reversed the first one fails because one Lead was created previously. What can I do?
public function testPotentialLeads()
{
factory(Lead::class)->create(['lead_type' => LeadType::POTENTIAL]);
factory(Lead::class)->create();
factory(Lead::class)->create();
$potential_leads = Lead::potentials()->get();
$this->assertEquals(1, $potential_leads->count());
$this->assertEquals(3, Lead::all()->count());
}
public function testAnotherLeadFunction()
{
$lead = factory(Lead::class)->create();
$this->assertTrue(true);
}
Upvotes: 1
Views: 1802
Reputation: 2639
I found my error. It was failing because when I was doing this:
factory(Lead::class)->create(['lead_type' => LeadType::POTENTIAL]);
factory(Lead::class)->create();
factory(Lead::class)->create();
$potential_leads = Lead::potentials()->get();
$this->assertEquals(1, $potential_leads->count());
$this->assertEquals(3, Lead::all()->count());
Two Leads were being generated with randomly LeadType (through the model factory) so there were some attempts when more potential leads were created.
Upvotes: 0
Reputation: 9455
First of all, this test isnt really a test: $this->assertTrue(true);
. If you wanted to test whether the lead was created, you should have used, $this->assertTrue($lead->exists());
If you want to run unit tests in a certain order, you can use the @depends annotation
The DatabaseTransactions
trait does rollback after every test and not after all tests
You might want to use the DatabaseMigrations
trait if you want to migrate and migrate rollback before and after every test rather than wrap them into transactions
If you want to use custom setup and teardown methods, use the afterApplicationCreated
and beforeApplicationDestroyed
methods instead to register callbacks
Upvotes: 2