Hi I am following the laravel course from laracast, but faced some difficulty following the course.
In the app, there is a Post Model with a static function that returns grouped records:
Post.php
public static function archives()
{
return static::selectRaw('year(created_at) as year, monthname(created_at) month, count(*) published')
->groupBy('year', 'month')
->orderByRaw('min(created_at) desc')
->get()
->toArray();
}
On the other hand, a test case aims to test the Post::archives() function:
ExampleTest.php
public function testBasicTest()
{
// GIVEN I have two records in the database that are posts,
// and each one is posted a month apart.
$first = factory(Post::class)->create();
$second = factory(Post::class)->create([
'created_at' => \Carbon\Carbon::now()->subMonth()
]);
// WHEN I fetch the archives
$posts = \App\Post::archives();
// dd($posts);
// THEN the response should be in the proper format
$this->assertEquals([
[
"year" => $first->created_at->format('Y'),
"month" => $first->created_at->format('F'),
"published" => 1
],
[
"year" => $first->created_at->format('Y'),
"month" => $first->created_at->format('F'),
"published" => 1
],
], $posts);
}
However, the assertion failed, because $posts is an array of object instead of an array of array, even though Post::archives() specifically converted the results with toArray().
Dumping it on tinker:
$posts = \App\Post::archives()
[
[
"year" => 2014,
"month" => "March",
"published" => 2,
],
[
"year" => 2014,
"month" => "February",
"published" => 1,
],
[
"year" => 2013,
"month" => "February",
"published" => 1,
],
]
clearly shows it as the proper format. Why is it behaving as such in the TestCase?
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire