alexhiggins's avatar

Odd test results

Hey Guys,

I have an issue with a couple of my tests. The problem is sometimes they're passing and sometimes they're failing. This really should not be the case at all.

I have a recipes, tags, and then the pivot for this (recipe_tag). I have to use DB::table as to my knowledge test dummy does not provide support for pivot tables. Here's one of the tests.

  /** @test */
  public function it_returns_recipes_by_tag()
  {
    $tags = Factory::times(2)->create('App\Tags\Tag');
    $recipes = Factory::times(2)->create('App\Recipes\Recipe');

    DB::table('recipe_tag')->insert([
      ['recipe_id' => $recipes[0]->id, 'tag_id' => $tags[0]->id],
      ['recipe_id' => $recipes[1]->id, 'tag_id' => $tags[0]->id],
      ['recipe_id' => $recipes[1]->id, 'tag_id' => $tags[1]->id],
    ]);

    list($tag, $recipeOne) = $this->repo->getByTag($tags[0]->slug);
    list($tag, $recipeTwo) = $this->repo->getByTag($tags[1]->slug);

    $this->assertCount(2, $recipeOne);
    $this->assertCount(1, $recipeTwo);
  }

And here's the method I am testing

  /**
   * @param     $slug
   * @param int $howMany
   * @return array
   */
  public function getByTag($slug, $howMany = 12)
  {
    $tag = $this->tag->whereSlug($slug);
    $recipes = $tag->recipes()->latest()->paginate($howMany);

    return [$tag, $recipes];
  }

Sometimes I get this

1) RecipeRepositoryTest::it_returns_recipes_by_tag
Illuminate\Database\Eloquent\ModelNotFoundException: No query results for model [App\Tags\Tag].

FAILURES!                            
Tests: 10, Assertions: 10, Errors: 1.

Others I get php OK (10 tests, 12 assertions)

So obviously there's something wrong but I don't see how I could improve this or what exactly is wrong.

Any advise?

Cheers

0 likes
1 reply

Please or to participate in this conversation.