多亏了这个食谱食谱,我有一个很好用的文件上传表单。但是它没有测试覆盖率,所以我编写了自己的断言,上传图像,检查图像是否已上传,然后删除图像并检查图像是否未显示在页面上。
他们都是第一次通过,包括最后断言检查图像(或图像的名称)不存在,但它没有删除它,我仍然在网页上看到它。因此,在此之后运行的任何测试都将失败,因为 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();
}