I have doctrine2 setup with ZF 1.11, I am having difficulty learning the best way to unit test controllers. I would like to be able to test actions in controllers without writing to the database within my unit tests however I am finding it impossible to actually do so.
For example say I have the following hypothetical action within my controller.
public function redirectUserAction() {
$registry = Zend_Registry::getInstance();
$em = $registry->entitymanager;
$user = $em->getRepository('Application_Model_User')
->findOneBy(array('email' => 'test@test.com'));
if(is_object($user)) {
$this->_redirect('/');
}
}
I want to test that if there is a user available with the email address test@test.com it will redirect to / so at the moment I have the following test.
public function testUserAvaliableShouldRedirectIndex() {
$registry = Zend_Registry::getInstance();
$em = $registry->entitymanager;
$user = new Application_Model_User();
$user->setEmail('test@test.com');
$em->persist($user);
$em->flush();
$this->dispatch('/index/redirect-user');
$this->assertRedirectTo('/');
$em->remove($user);
$em->flush();
}
This seems to me like a very messy way of writing tests. I was under the impression that with doctrine I wouldn’t need to actually flush to the database because my objects would be stored in the persistence layer but at the moment my tests fail without flushing.
If anyone knows a better way I could write tests or can help me see where I am going wrong I would be very grateful.
Thanks
Instead of creating and deleting the user in
testUserAvaliableShouldRedirectIndex()you could usesetUp()andtearDown()to create and delete the user. This way you can use that user throughout all actions that expect an existing user, like yourredirectUserAction(),loginAction(), etc. instead of having to do what you currently do for each of these actions.