Warm tip: This article is reproduced from serverfault.com, please click

php-为什么仅在PHPUnit测试中才禁止返回请求?

(php - Why is a request returning forbidden only in PHPUnit testing?)

发布于 2020-03-30 09:27:45

我在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。缺少什么?

Questioner
Rory
Viewed
0
Rory 2020-03-30 17:42:52

通过编辑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的值都转储预期值时。