首页 > 解决方案 > deleteFileAfterSend Laravel 响应不会在测试中删除文件

问题描述

我有 laravel 5.5 应用程序。
我正在尝试使用 laravel snappy 对下载 PDF 进行测试。

到目前为止,我的CheckTest.php中有一个函数:

public function testPrintCheck(){

   $check = $this->createCheck();
   $route ="/api/checks/print/$check->id";
   $response = $this->get($route);
   $this->assertEquals($response->headers->get('content-type') , 'application/pdf');
   $response->assertStatus(200);
 }

在我的控制器中,我有:

public function printCheck(Request $request, Check $check){
   $pdf = \PDF::loadView("pdf.check");
   $file= storage_path(). "/app/checks/$check->id.pdf";
   $pdf->save($file);
   $headers = array(
      'Content-Type: application/pdf'
   );
   return response()->download($file, "check_n_$check->id.pdf", $headers)->deleteFileAfterSend(true)->setStatusCode(200);

}

当前测试有效,但我希望删除下载后创建的文件(使用deleteFileAfterSend(true)),但该文件不会被删除。

因此,如果我添加断言该文件不存在,它将失败。

标签: laravelunit-testing

解决方案


根据不久前在 github 上创建的问题,有一个可能的解决方案: https ://github.com/laravel/framework/issues/36286

使用 Laravel 8.24

基本上我们需要强制发送文件内容,然后触发文件删除

public function test(): void
{
    $response = $this->get('url/to/download');

    // Here the file is not deleted yet

    $response->sendContent();

    // Here the file is deleted
}

推荐阅读