感谢this cookbook recipe,我有一个很好的文件上传表单。但是它没有进行测试覆盖,因此我编写了自己的断言,上传图像,检查图像是否已上传,然后删除图像并检查图像是否未在页面上显示。
它们都是第一次通过,包括检查图像(或图像名称)不存在的最终断言,但它不会删除它,我仍然在网页上看到它。因此,在此之后运行的任何测试都将失败,因为Crawler会找到旧条目。为什么会这样?
测试
public function testUploadScenario()
{
// Upload image
$crawler = $client->click($crawler->selectLink('Upload')->link());
$this->assertEquals(1, $crawler->filter('html:contains("Upload file attachment")')->count());
$pathToTestUploadFile = static::$kernel->getRootDir().'/../src/Acme/MyBundle/Resources/public/logo.gif';
$uploadForm = $crawler->selectButton('Upload')->form();
$uploadForm['upload[name]'] = "Logo Test";
$uploadForm['upload[file]']->upload($pathToTestUploadFile);
$crawler = $client->submit($uploadForm);
// Check that the session flash message confirms the attachment was uploaded.
$this->assertTrue($client->getResponse()->isSuccessful());
$this->assertEquals(1, $crawler->filter('html:contains("File uploaded")')->count());
// Delete the image
$crawler = $client->submit($crawler->selectButton('Delete')->form());
$this->assertEquals(0, $crawler->filter('html:contains("Logo Test")')->count());
$this->assertEquals(1, $crawler->filter('html:contains("File has been deleted")')->count());
}
控制器
/**
* Finds and displays an attachment.
*
* @param integer $id
*/
public function showAction($id)
{
$em = $this->getDoctrine()->getManager();
$attachment = $em->getRepository('AcmeMyBundle:Attachment')->find($id);
if (!$attachment) {
throw $this->createNotFoundException('Unable to find attachment file.');
}
return $this->render('AcmeMyBundle:Attachment:show.html.twig', array(
'attachment' => $attachment,
'delete_form' => $this->createDeleteForm($id)->createView()
));
}
/**
* Deletes an attachment file from the database.
*
* @param Request $request
* @param integer $id
*
* @return Response
*/
public function deleteAction(Request $request, $id)
{
$form = $this->createDeleteForm($id);
$form->bind($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$attachment = $em->getRepository('AcmeMyBundle:Attachment')->find($id);
if (!$attachment) {
throw $this->createNotFoundException('Unable to find attachment file.');
}
$em->remove($attachment);
$em->flush();
}
$this->getRequest()->getSession()->getFlashBag()->add('notice', 'File has been deleted.');
return $this->redirect($this->generateUrl('attachment_index'));
}
/**
* Creates a form to delete an attachment file by id.
*
* @param mixed $id The attachment id
*
* @return Symfony\Component\Form\Form The form
*/
private function createDeleteForm($id)
{
return $this->createFormBuilder(array('id' => $id))->add('id', 'hidden')->getForm();
}
答案 0 :(得分:2)
无论提交的表单是否有效,您都会添加Flash通知。
您正在检查是否存在“文件已被删除”。但通知没有添加到if语句中。
if ($form->isValid()) {
// ...
$this->getRequest()->getSession()->getFlashBag()->add('notice', 'File has been deleted.');
}
您应该在try-catch块中进一步包装$em->remove($entity)
,因为如果您要在pre / postRemove侦听器中删除该文件,则仍然可能发生该实体有效但该文件无法删除到期即导致异常的权限问题。