【问题标题】:How to Set Up a Test for the Destroy Method Laravel 5.6如何为销毁方法 Laravel 5.6 设置测试
【发布时间】:2019-07-29 11:32:52
【问题描述】:

我正在对我的应用程序进行测试,我已经到了需要测试我的控制器的销毁方法的地步。我目前的测试是:

public function test_user_can_delete_draft()
{
  $user = factory(User::class)->states('confirmed', 'normaluser')->create();
  $userForm = factory(Form::class)->states('in_house_signs')->create(['user_id' => $user->id, 'status' => 'draft',]);
  // Test creator can delete form
  $response = $this->actingAs($user)->delete(route('forms.destroy', $userForm));
  $response->assertSuccessful();
}

我正在测试的控制器中的方法是:

public function destroy($id) {
   $form = Form::find($id);
   Comment::where('form_id', $id)->delete();
   $form->delete();

   // Redirect
   return redirect()->back()->with('status', 'Form successfully deleted');
}

当我运行 phpunit 时,我得到了错误:

Response status code [302] is not a successful status code.
Failed asserting that false is true.

我应该怎么做才能让测试正常运行?

【问题讨论】:

    标签: php laravel laravel-5.6 laravel-testing


    【解决方案1】:

    你可以尝试使用assertRedirecthttps://laravel.com/docs/5.6/http-tests#assert-redirect

    或使用状态检查:

    $response->assertStatus(302)https://laravel.com/docs/5.6/http-tests#assert-status

    或者如果你真的想检查记录是否被删除,你可以在你的测试中检查数据库,如果记录被删除$this->assertEquals(Comment::where('form_id', $userForm->id)->first(),null)

    【讨论】:

    • 我将控制器从redirect()->改回redirect()->route,并将测试更改为匹配,现在它通过了!谢谢你的提示!
    【解决方案2】:

    您正在使用$response->assertSuccessful(); 并重定向用户,我的意思是如果您的删除请求成功,它将返回302 重定向,请将assertSuccessful() 更改为assertStatus(302)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-24
      • 1970-01-01
      相关资源
      最近更新 更多