brslv brslv - 1 year ago 95
PHP Question

Database transactions doesn't prevent id incrementation when testing in Laravel

So, in Laravel 5.3 I have the following test:

class ArticleTest extends TestCase
use DatabaseTransactions;

/** @test */
public function it_fetches_trending_articles()
factory(Article::class, 3)->create();
factory(Article::class)->create(['reads' => 10]);
$mostPopular = factory(Article::class)->create(['reads' => 20]);

$articles = Article::trending();

$this->assertEquals($mostPopular->id, $articles->first()->id);

What's going on here is I create 3 articles with no 'reads' info, one article with 10 reads and one with 20 reads. I get the articles, ordered by 'reads' and take the first one and assert it's id is equal to the one I'm sure is the most trending. The test passes and everything is ok.

The problem, though, is that the DatabaseTransactions trait does not work as expected. Yeah, it doesn't save the articles to the database, but it keeps increasing the id count on each test run.

It would be great if you give me some advice on how to prevent this kind of behaviour.

Thanks in advance. :)

Answer Source

You'd have to use DatabaseMigrations. Even when the transaction is reversed, the database increments the primary key. It has to, otherwise you might have other issues in your app with repeating primary keys.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download