1
votes

I'm testing an application made with cake and I found a problem when testing an add method. The problem in fact is that whenever I want to test saving data on the DB, after making a sample data to send with the request, I found out that that data is saved on the DB but with just the id attribute set. The other fields are null.

Here's the method I want to test:

public function admin_add() {
    if ($this->request->is('post')) {
        debug($this->request->data);
        $this->Item->create();
        if ($this->Item->save($this->request->data)) {
            $this->Session->setFlash(__('The item has been saved'));
            //$this->redirect(array('action' => 'index'));
        } else {
            $this->Session->setFlash(__('The item could not be saved. Please, try again.'));
        }
    }
    $products = $this->Item->Product->find('list');
    $attributes = $this->Item->Attribute->find('list');
    $this->set(compact('products', 'attributes'));
}

And here's my test:

public function testAdmin_add(){

 $this->Items->request->params['action'] = 'admin_add';
 $this->Items->request->params['url']['url'] = 'admin/items/add';
 $data = array(
  'Item' => array(
    'product_id' => 1,
    'attribute_id' => 9,
    'title' => 'test_item',
    'code' => 1,
    'in_stock' => 1,
    'batched_stock'=> 1,
    'allocated' => 0,
  ),
 );

    $this->Collection = $this->getMock('ComponentCollection');
  $this->Items->Session = $this->getMock('SessionComponent', array('setFlash'), array($this->Collection));

  $this->Items->Session->expects($this->once())
        ->method('setFlash')
        ->with(__d('items', 'Se ha guardado el item'));


 $this->__setPost($data);

 $this->Items->admin_add();

}

Notice that if I run this test I'll have an extra field on the db, and because table's id is auto-increment I cant get the id back to delete that entry.
Now the question is: is there any way I can test DB saving without actually save data on it?

Thanks!

1
Another thing: the test doesn't work if I uncomment the line $this->redirect in the add method. - Joaquin Rodriguez

1 Answers

0
votes

To prevent saving data, you'll want to use Fixtures. Here is the documentation based on what version of CakePHP you are using:

Make sure to use a test database or you'll find that after each test is run, your tables will be dropped.