Cake で作成したアプリケーションをテストしていて、add メソッドのテスト中に問題が見つかりました。実際の問題は、DB にデータを保存することをテストしたいときはいつでも、リクエストで送信するサンプル データを作成した後、そのデータが DB に保存されているが、id 属性が設定されているだけであることがわかりました。他のフィールドは null です。
テストしたい方法は次のとおりです。
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'));
}
そして、ここに私のテストがあります:
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();
}
このテストを実行すると、データベースに追加のフィールドが作成されます。テーブルの ID は自動インクリメントであるため、ID を取得してそのエントリを削除することはできません。
ここで問題は、実際にデータを保存せずに DB の保存をテストする方法はありますか?
ありがとう!