I have a category model with the following method:
JavaScript
x
public static function index()
{
return self::has('posts')->paginate(1);
}
My category controller:
JavaScript
public function index()
{
$categories = Category::index();
return view('categories.index', compact('categories'));
}
This is what I’ve tried, I am using RefreshDatabase trait.
JavaScript
public function test_index_view_is_working()
{
factory(Post::class, 5)->create();
$response = $this->get(route('categories.index'));
$response->assertViewHas('categories', Category::index());
}
This test fails for some reason:
JavaScript
Failed asserting that two objects are equal.
at tests/Feature/CategoryTest.php:38
37| $response->assertViewIs('categories.index');
> 38| $response->assertViewHas('categories', Category::index());
--- Expected
+++ Actual
@@ @@
'dispatchesEvents' => Array ()
'observables' => Array ()
'relations' => Array (
+ 'posts' => IlluminateDatabaseEloquentCollection Object ( )
)
'touches' => Array ()
'timestamps' => true
Advertisement
Answer
The reason you get this error is because somehow the posts
are eager loaded from the view/controller but not from the tests.
I’m guessing return self::has('posts')->with('posts')->paginate(1);
could fix it.
Alternatively, you can test if you have the pagination at the bottom the page. Since {{ $categories->links() }}
will add something like Previous
and Next
you can still look for it.
JavaScript
$response = $this->get(route('categories.index'));
$response->assertSee('Next');
Also, you can ensure that you paginate the categories but it won’t ensure you have added the links at the bottom of the page.
JavaScript
use IlluminateContractsPaginationPaginator;
$response = $this->get(route('categories.index'));
$this->assertInstanceOf(Paginator::class, $response->viewData('categories'));