Summer Sale! All accounts are 50% off this week.

hafix's avatar
Level 2

Failed asserting that a row in the table [employees] matches the attributes

Hello Everyone, I am following Build A Laravel App With TDD series from laracasts . Though it's a old series . I am getting an error while testing. Sometimes I get an error on a test and sometimes test passes. I am unable to fix the error. When I get an error it says Failed asserting that a row in the table [employees] matches the attributes

This is my code for test

class EmployeeTest extends TestCase
{
    use withFaker, RefreshDatabase;

    public function test_create_employee()
    {
        $this->withoutExceptionHandling();
        $attributes = [
            'name' => $this->faker->name,
            'office_id' => $this->faker->numerify('3###'),
            'designation' => $this->faker->jobTitle(),
            'email' => $this->faker->unique()->safeEmail(),
            'mobile' => $this->faker->numerify('017########'),
            'status' => $this->faker->numberBetween(1, 3),
        ];

        $this->post('employee', $attributes);
        $this->assertDatabaseHas('employees', $attributes);

    }

}

This is the error

https://ibb.co/qr97nQ5

If i run the test several time the test pass too.

0 likes
9 replies
Sinnbeck's avatar

Seems the problem is that the status is a random number between 1 and 3. My guess is that your post route does not set the same number. So 1 in 3 chance for it to pass. Show the method please

1 like
Sinnbeck's avatar

Maybe the field isn't fillable and the default in the database is 1?

hafix's avatar
Level 2

@Sinnbeck i had unguard the fields so that might not be a problem. But the random number is making this problem. when I set the number to 1/2/3 integer that fixes the problem. Yes the database default value is set to 1 which is a tiny integer.

Can you explain why random value is making this problem?

Sinnbeck's avatar

Same bug in update. This is why tests are great :)

1 like
hafix's avatar
Level 2

@Sinnbeck Thanks for pointing it out but i want to know that. I was creating data through factory. Using the post method does that means the create method of controller also called automatically as model is using hasfactory.

Sinnbeck's avatar

@hafix using a factory is not the same as creating in the controller. But your code shows no sign of a factory being used. You only use faker to make the attributes, which isn't a factory

If the problem is solved, please mark a best answer

Please or to participate in this conversation.