2012-04-16 32 views
2

一個附加功能,我已被告知,我們也測試通過蛋糕像添加/刪除創建的功能...我如何可以測試CakePHP2.0

如果我有這樣一個功能,怎麼樣如果它沒有任何回報,重定向或甚至視圖,我可以測試它嗎? (我使用AJAX來執行它)

public function add() { 
     if ($this->request->is('post')) { 
      $this->Comment->create(); 
      if ($this->Comment->save($this->request->data)) { 
       $this->Session->setFlash(__('The comment has been saved')); 
      } else {     
       $this->Session->setFlash(__('The comment could not be saved. Please, try again.')); 
      } 
     } 
    } 

感謝

回答

1
public function add() { 
     $this->autoRender = false; 
     if ($this->request->is('post')) { 
      $this->Comment->create(); 
      if ($this->Comment->save($this->request->data)) { 
       echo json_encode(array('status' => 'ok')); 
      } else { 
       echo json_encode(array('status' => 'fail'));    
      } 
     } 
    } 
+0

謝謝夥計!但是......這不是更好,而不是回聲? (數組('status'=>'ok')));}}; 然後正確解碼。 – Alvaro 2012-04-16 17:57:22

+1

@Steve yup,你可以使用$ this-> response-> body()。 TNX .. – thecodeparadox 2012-04-16 17:58:32

2

這裏有一種通用的方式來測試它。

function testAdd() { 
    $Posts = $this->generate('Posts', array(
    'components' => array(
     'Session', 
     'RequestHandler' => array(
     'isAjax' 
    ) 
    ) 
)); 
    // simulate ajax (if you can't mock the magic method, mock `is` instead 
    $Posts->RequestHandler 
    ->expects($this->any()) 
    ->method('isAjax') 
    ->will($this->returnValue(true)); 
    // expect that it gets within the `->is('post')` block 
    $Posts->Session 
    ->expects($this->once()) 
    ->method('setFlash'); 

    $this->testAction('/posts/add', array(
    'data' => array(
     'Post' => array('name' => 'New Post') 
    ) 
)); 
    // check for no redirect 
    $this->assertFalse(isset($this->headers['Location'])); 
    // check for the ajax layout (you'll need to change 
    // this to check for something in your ajax layout) 
    $this->assertPattern('/<html/', $this->contents); 
    // check for empty view (I've never had an empty view but try it out) 
    $this->assertEqual('', $this->view); 
} 
相關問題