Welcome to the Cookbook

loading...

4.7.6 Testing controllers

4.7.6.1 Creando un test case

Digamos que tienes un típico controlador de artículos, con su correspondiente modelo, y que se parece a éste:

<?php 
class ArticlesController extends AppController { 
   var $name = 'Articles'; 
   var $helpers = array('Ajax', 'Form', 'Html'); 
   
   function index($short = null) { 
     if (!empty($this->data)) { 
       $this->Article->save($this->data); 
     } 
     if (!empty($short)) { 
       $result = $this->Article->findAll(null, array('id', 
          'title')); 
     } else { 
       $result = $this->Article->findAll(); 
     } 
 
     if (isset($this->params['requested'])) { 
       return $result; 
     } 
 
     $this->set('title', 'Articles'); 
     $this->set('articles', $result); 
   } 
} 
?>
  1. <?php
  2. class ArticlesController extends AppController {
  3. var $name = 'Articles';
  4. var $helpers = array('Ajax', 'Form', 'Html');
  5. function index($short = null) {
  6. if (!empty($this->data)) {
  7. $this->Article->save($this->data);
  8. }
  9. if (!empty($short)) {
  10. $result = $this->Article->findAll(null, array('id',
  11. 'title'));
  12. } else {
  13. $result = $this->Article->findAll();
  14. }
  15. if (isset($this->params['requested'])) {
  16. return $result;
  17. }
  18. $this->set('title', 'Articles');
  19. $this->set('articles', $result);
  20. }
  21. }
  22. ?>

Crea un archivo llamado articles_controller.test.php y pon lo siguiente dentro:

<?php 
class ArticlesControllerTest extends CakeTestCase { 
   function startCase() { 
     echo '<h1>Comenzando Test Case</h1>'; 
   } 
   function endCase() { 
     echo '<h1>Terminado Test Case</h1>'; 
   } 
   function startTest($method) { 
     echo '<h3>Comenzando método ' . $method . '</h3>'; 
   } 
   function endTest($method) { 
     echo '<hr />'; 
   } 
   function testIndex() { 
     $result = $this->testAction('/articles/index'); 
     debug($result); 
   } 
   function testIndexShort() { 
     $result = $this->testAction('/articles/index/short'); 
     debug($result); 
   } 
   function testIndexShortGetRenderedHtml() { 
     $result = $this->testAction('/articles/index/short', 
     array('return' => 'render')); 
     debug(htmlentities($result)); 
   } 
   function testIndexShortGetViewVars() { 
     $result = $this->testAction('/articles/index/short', 
     array('return' => 'vars')); 
     debug($result); 
   } 
   function testIndexFixturized() { 
     $result = $this->testAction('/articles/index/short', 
     array('fixturize' => true)); 
     debug($result); 
   } 
   function testIndexPostFixturized() { 
     $data = array('Article' => array('user_id' => 1, 'published' 
          => 1, 'slug'=>'new-article', 'title' => 'New Article', 'body' => 'New Body')); 
     $result = $this->testAction('/articles/index', 
     array('fixturize' => true, 'data' => $data, 'method' => 'post')); 
     debug($result); 
   } 
} 
?> 
  1. <?php
  2. class ArticlesControllerTest extends CakeTestCase {
  3. function startCase() {
  4. echo '<h1>Comenzando Test Case</h1>';
  5. }
  6. function endCase() {
  7. echo '<h1>Terminado Test Case</h1>';
  8. }
  9. function startTest($method) {
  10. echo '<h3>Comenzando método ' . $method . '</h3>';
  11. }
  12. function endTest($method) {
  13. echo '<hr />';
  14. }
  15. function testIndex() {
  16. $result = $this->testAction('/articles/index');
  17. debug($result);
  18. }
  19. function testIndexShort() {
  20. $result = $this->testAction('/articles/index/short');
  21. debug($result);
  22. }
  23. function testIndexShortGetRenderedHtml() {
  24. $result = $this->testAction('/articles/index/short',
  25. array('return' => 'render'));
  26. debug(htmlentities($result));
  27. }
  28. function testIndexShortGetViewVars() {
  29. $result = $this->testAction('/articles/index/short',
  30. array('return' => 'vars'));
  31. debug($result);
  32. }
  33. function testIndexFixturized() {
  34. $result = $this->testAction('/articles/index/short',
  35. array('fixturize' => true));
  36. debug($result);
  37. }
  38. function testIndexPostFixturized() {
  39. $data = array('Article' => array('user_id' => 1, 'published'
  40. => 1, 'slug'=>'new-article', 'title' => 'New Article', 'body' => 'New Body'));
  41. $result = $this->testAction('/articles/index',
  42. array('fixturize' => true, 'data' => $data, 'method' => 'post'));
  43. debug($result);
  44. }
  45. }
  46. ?>

4.7.6.2 El método testAction

La novedad aquí es el método testAction. El primer argumento de este método es la URL "en formato Cake" de la acción del controlador que se quiere probar, como en '/articles/index/short'.

El segundo argumento es un array de parámetros, consistente en:

return
Indica lo que se va a devolver.
Los valores válidos son:
  • 'vars' - Obtienes las variables de la vista disponibles tras ejecutar la acción
  • 'view' - Obtienes la vista generada, sin layout
  • 'contents' - Obtienes todo el html de la vista, incluyendo layout
  • 'result' - Obtienes el valor de retorno de la acción como cuando se usa $this->params['requested'].
El valor por defecto es 'result'.
fixturize
Ponlo a true si quieres que tus modelos se "auto-simulen" (de modo que las tablas de la aplicación se copian, junto con los registros, para que al probar las tablas si cambias datos no afecten a tu aplicación real.) Si en 'fixturize' pones un array de modelos, entonces sólo esos modelos se auto-simularán mientras que los demás utilizarán las tablas reales. Si quieres usar tus archivos de fixtures con testAction() no uses fixturize, y en su lugar usa las fixtures como harías normalmente.
method
Ajustalo a 'post' o 'get' si quieres pasarle datos al controlador
data
Los datos que se pasarán. Será un array asociativo consistente en pares de campo => valor. Échale un vistazo a function testIndexPostFixturized() en el case test de arriba para ver cómo emulamos pasar datos de formulario como post para un nuevo artículo.

4.7.6.3 Pitfalls

Todavia no hay una traducion de este texto. Por favor ayudanos y traducirla.. Mas info sobre traduciones

If you use testAction to test a method in a controller that does a redirect, your test will terminate immediately, not yielding any results.
See https://trac.cakephp.org/ticket/4154 for a possible fix.

For an in-depth explanation of controller testing please see this blog post by Mark Story Testing CakePHP Controllers the hard way.