我在Laravel 6项目中遇到测试类问题。由于返回的响应403 forbidden
不是视图,因此以下测试失败。但是,我只能在测试中重现它-在主应用程序中,它按预期返回视图。有没有人经历过类似的事情,或者在下面可以看到明显错误的东西?
ProductTest.php
public function testUsersCanViewTheirOwnProducts(){
$user = Factory(User::class)->create();
$product = Factory(Product::class)->create(['user_id'=>$user->id]);
$this->actingAs($user);
$response = $this->get(route('show_product',['product'=>$product->id]));
$response->assertViewIs('products.show'); //Fails not a view (403 forbidden when response dumped)
$response->assertViewHas('product',$product);
}
倾销$user->id
和$product->id
退货1
均符合预期。
ProductController.php
public function __construct()
{
$this->authorizeResource(Product::class, 'product');
}
//...
public function show(Product $product)
{
return view("products.show",['product'=>$product]);
}
ProductPolicy.php
public function view(User $user, Product $product)
{
return $user->id === $product->user_id;
}
testing.env
//identical to .env apart from
TELESCOPE_ENABLED=false
DB_DATABASE=subscribe_test
路线/web.php
Route::get('/manage/products/{product}','ProductController@show')->middleware('auth')->name('show_product');
我清除了所有缓存,但没有任何效果。资源在PHPUnit测试中返回403,在应用程序中返回200。缺少什么?
通过编辑phpunit.xml
文件,我已经在测试中获得了预期的响应,事实证明,该文件已覆盖了我的文件.env.testing
。
删除这两行给出了预期的行为。
<server name="DB_CONNECTION" value="sqlite"/>
<server name="DB_DATABASE" value=":memory:"/>
让我期望.env.testing
给:
DB_CONNECTION=mysql
DB_DATABASE=subscribe_test
但是我不明白为什么这会在SQLLite上失败?特别是当用于比较ID的值都转储预期值时。
好吧,这实际上也为我解决了这个问题,但是我不知道为什么只有Sqlite会发生这种情况。现在我的测试速度变慢了。