问题
Hi I have this unit test
public function test_index_coupon(){
$coupons = factory(App\Models\Coupon::class, 5)->create();
$this->visit('/admin/coupons')
->assertResponseOk()
->assertViewHasAll('coupons');
}
Here is my controller to list index of coupons
public function index()
{
$coupons = Coupon::all();
return view('backend.admin.coupons.index', compact('coupons'));
}
And I can successfully list coupons with
@foreach($coupons as $coupon)
.....
@endforeach
In my view, I check it via browser.
But when I run phpunit
I get this error
1) CouponsTest::test_index_coupon
ErrorException: Argument 1 passed to Illuminate\Foundation\Testing\TestCase::assertViewHasAll() must be of the type array, string given, called in /var/www/html/rentcar/tests/admin/CouponsTest.php on line 24 and defined
Then I try modify my test from ->assertViewHasAll('coupons');
to ->assertViewHas('coupons');
and I get different error
1) CouponsTest::test_index_coupon
Failed asserting that an array has the key 'coupons'.
Whats wrong with my test code? I just want to check if visit admin/coupons
coupons list loaded properly. so I can make sure if $coupons
is exists in view.
UPDATE
It works with assertViewHas('coupons')
don't know why, maybe something wrong with my entire test code or maybe because use WithoutMiddleware
Thanks for answer and comment.
回答1:
$this->visit('/admin/coupons')
->assertResponseOk()
->assertViewHas('coupons', $coupons);
OR (int case you plan on adding more data to assert in assertViewHasAll
)
$this->visit('/admin/coupons')
->assertResponseOk()
->assertViewHasAll(['coupons' => $coupons]);
回答2:
In the Laravel documentation, you can see that assertViewHasAll
recives an array as parameter.
->assertViewHasAll(array $bindings);
And you are giving it a string:
->assertViewHasAll('coupons');
来源:https://stackoverflow.com/questions/40138855/laravel-5-2-phpunit-assertviewhasall-failed