Ifrit's avatar
Level 2

Getting my test to work

I'm trying to create a test that will add a state to the database. The problem I'm getting is I get this error when running the test

Failed asserting that false is true.

Which is kind of correct in a sense that whatever I did isn't inserting the data to the table, but what I really want is for it to save to the database and pass.

Here is my code for my test

public function testAddNewState()
{
    $country = Country::all()->first();

    $response = $this->post('/api/admin/country/'.$country->id.'/new-state', [
        'state' => 'Texas'
    ]);

    $response->assertStatus(302);
    $this->assertTrue(count(State::all()) > 1);
}

this is the controller that the api points to

public function addNewState(Country $country)
{
    $new = $country->states()->create([
        'state' => request('state');
    ]);

    return [
        'new' => $new
    ]
}
0 likes
5 replies
Tray2's avatar

Change

$this->assertTrue(count(State::all()) > 1);

To

$this->assertDatabaseCount('states',5);

And see what it says.

Ifrit's avatar
Level 2

I got

Failed asserting that table [states] matches expected entries count of 5. Entries found > 0

Tray2's avatar

Well that means it never creates a record in the database.

Robstar's avatar

You'd save yourself a lot of time by reading the excellent documentation Laravel provides.

  • Step 1 - read about model factories
  • Step 2 - use a factory within your test class i.e. $user = User::factory()->make()

For your use case, assuming you're using the default Laravel phpunit settings, it that a country doesn't exist or, you;'re using the refresh database trait of your test database is being cleared after previous tests.

Unrelated, I'd highly recommend using restful conventions. So your addNewState method would be namedto store.

Also you're API method just returns an array without the expected status code. Ideally, instead of

return [
        'new' => $new
    ]

you'd return

return response()->json(compact('new'), 201);

Within your tests you can not only test for the expected returned content, but also the http status code.

However, biggest advice, read the Laravel documentation or watch the plethora of tutorials available on Laracasts.

Please or to participate in this conversation.