jove's avatar
Level 7

UnitTests how to get ID of created model or wipe DB each test?

So my current issue is that I hardcode the ID

$response = $this->post(route('admin.books.store'), $attributes);
$response->assertRedirect(route('admin.books.show', 1));

Now this started to fail after I added a bunch more tests because when it arrives at this it fails to match the ID of 1 is equal to 7. How can I get the ID of the new book created in the post or have a clean state after each test?

I have this in my TestCase

use CreatesApplication, RefreshDatabase;

but that seems to only be each start?

0 likes
3 replies
Nakov's avatar
Nakov
Best Answer
Level 73

@jove

The RefreshDatabase trait does wipe the data on each test: https://laravel.com/docs/master/database-testing#resetting-the-database-after-each-test

It depends what your $attributes are. Are you calling factory(Post::class)->create() above, because that will persist a row, in which case the ID will get incremented.

What I usually do is use $post = factory(Post::class)->raw() and pass that to the post, then just use $post->fresh()->id which should give you the correct id.

1 like
jove's avatar
Level 7

@nakov $post->fresh()->id but this is an array? That doesn't work does it? I get this at least Error : Call to a member function fresh() on array

Nakov's avatar

@jove Yes, so the raw returns an array. So basically this is the flow that I use:

$post = factory(Post::class)->raw([ 'user_id' => $user->id ]);

$response = $this->call('post', route('dmin.books.store'), $post)
            ->assertSuccessful();

// here because I return the created resource from the controller:

$response->id; // is what I need
1 like

Please or to participate in this conversation.