0

I start to write unittests for controllers in cakephp 2.5 and struggle with a testmethod for the the delete method.

Controller:

public function delete($id = null)
{
    $this->Content->id = $id;
    if (!$this->Content->exists()) {
        throw new NotFoundException(__('Invalid content'));
    }
    $this->Content->recursive = -1;
    $content = $this->Content->findById($id);
    debug($content);
    if ($this->Content->delete($id)) {
        $this->Session->setFlash(__('Content deleted'), 'flash_success');
        return $this->redirect(array('action' => 'search'));
    } else {
        $this->Session->setFlash(__('Content was not deleted'), 'flash_error');
        return $this->redirect(array('action' => 'view', $id));
    }
}

Test:

$this->testAction(
        '/contents/delete/11');
    $this->assertContains('/contents/search', $this->headers['Location']);

However the $this->headers['Location'] is just myDomain.com instead of myDomain.com/contents/search although the Content with id 11 is in my testDB. So of course my test fails. By the way deleting in my real application works, so I guess the problem is the assertion and not the code of my app.

What would be the correct approach for a test of the delete method?

Calamity Jane
  • 2,189
  • 5
  • 36
  • 68
  • In your test you can get a model. Do a count-query before the `testAction`-method, and after the method. Assert on the count-query before, and assert on the count-query after the `testAction`. It looks dirty but should be working ;) – Bob Jan 17 '15 at 16:48
  • I thought about that, too. But as you say it is dirty. You test if the Item is deleted , but not if the view you want is displayed afterwards. I hope there is a cleaner way to do this. – Calamity Jane Jan 19 '15 at 09:03
  • Yeah you are right. I know a way to check its view or redirect. I will look at it this afternoon. ;) – Bob Jan 19 '15 at 09:15

1 Answers1

-1

Do you send back proper HTTP status code headers?

Typically I test that the delete returned a HTTP 204: No Content header

STLMikey
  • 1,210
  • 7
  • 19