1

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

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.

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

4

2 回答 2

1

你可以尝试使用assertRedirect https://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)

于 2019-03-07T14:36:18.593 回答
0

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

于 2019-03-07T14:37:51.760 回答