2012-04-16 1 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

Спасибо чувак! Но ... не лучше ли это вместо эха? \t \t \t \t $ this-> response-> body (json_encode (array ('status' => 'ok'))); Чтобы правильно декодировать его. – Alvaro

+1

@Steve yup, вы можете использовать $ this-> response-> body(). Tnx .. – thecodeparadox

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); 
} 

 Смежные вопросы

  • Нет связанных вопросов^_^