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

bearbytestudio's avatar

Why do my tests sporadically fail/pass?

I'm writing some pretty basic tests to assert that a project has been created and that an event is fired.

This first test will fail 50% of the time, and pass 50% of the time:

    /** @test */
    public function an_authenticated_user_can_create_a_project()
    {
        $name = 'This is the project name';
        $project = Project::factory()->make(['name' => $name])->toArray();

        // Logged out
        $response = $this->post(route('projects.store'), $project);
        $response->assertRedirect('/login');
        $this->assertDatabaseMissing('projects', $project);

        // Logged in
        $this->signIn($user = User::factory()->create());
        $project = Project::factory()->make([
            'name' => $name,
            'creator_id' => $user->id
        ])->toArray();
        $response = $this->post(route('projects.store'), $project);
        $this->assertDatabaseHas('projects', ['name' => $name]);
    }

The failure message is:

  • Tests\Feature\App\Http\Controllers\ProjectTest > an authenticated user can create a project
  Failed asserting that a row in the table [projects] matches the attributes {
      "name": "This is the project name"
  }.
  
  The table is empty..

I'm using the RefreshDatabase trait in the tests.

The second that fails 50% of the time is:

/** @test */
public function a_project_created_event_is_dispatched_on_project_created()
{
    $this->signIn();
    Event::fake();
    $this->post(route('projects.store'), Project::factory()->make()->toArray());
    Event::assertDispatched(ProjectCreated::class);
}

Failure:

  • Tests\Feature\App\Http\Controllers\ProjectTest > a project created event is dispatched on project created
  The expected [App\Events\ProjectCreated] event was not dispatched.
  Failed asserting that false is true.

Here is the basic controller method I'm testing:

public function store(CreateProjectRequest $request)
{
    $project = Project::create([
        ...$request->validated(),
        'creator_id' => auth()->id()
    ]);

    ProjectCreated::dispatch($project);

    return Redirect::back();
}

Any help welcome, I just don't understand why sometimes they pass and sometimes they fail?!

0 likes
3 replies
tisuchi's avatar

@fueltheweb What do you actually get using dd()?

e.g.-

public function store(CreateProjectRequest $request)
{
  dd($request->all());
}

Inspect your test output now.

MohamedTammam's avatar

Don't use Project::factory()->make()->toArray() and create the array yourself. Maybe you have some setters, getters or castings that change the value from what it's actually in the DB.

And also make sure that the request passed using ->assertOk(), before you check for existence in the database

$response->assertOk();

Please or to participate in this conversation.