How to test controllers with CodeIgniter? How to test controllers with CodeIgniter? codeigniter codeigniter

How to test controllers with CodeIgniter?


Alternatively, you could do this:

$CI =& get_instance();$CI = load_class('Loader');class MockLoader extends CI_Loader{    function __construct()    {        parent::__construct();    }}

Then in your controller do $this->load = new MockLoader().


My current solution is to alter the CodeIgniter code to use require_once instead of require. Here's the patch I'm going to send to CI developers in case someone needs to do the same until they accept it:

diff --git a/system/codeigniter/Common.php b/system/codeigniter/Common.php--- a/system/codeigniter/Common.php+++ b/system/codeigniter/Common.php@@ -100,20 +100,20 @@ function &load_class($class, $instantiate = TRUE)        // folder we'll load the native class from the system/libraries folder.        if (file_exists(APPPATH.'libraries/'.config_item('subclass_prefix').$class.EXT))        {-               require(BASEPATH.'libraries/'.$class.EXT);-               require(APPPATH.'libraries/'.config_item('subclass_prefix').$class.EXT);+               require_once(BASEPATH.'libraries/'.$class.EXT);+               require_once(APPPATH.'libraries/'.config_item('subclass_prefix').$class.EXT);                $is_subclass = TRUE;        }        else        {                if (file_exists(APPPATH.'libraries/'.$class.EXT))                {-                       require(APPPATH.'libraries/'.$class.EXT);+                       require_once(APPPATH.'libraries/'.$class.EXT);                        $is_subclass = FALSE;                }                else                {-                       require(BASEPATH.'libraries/'.$class.EXT);+                       require_once(BASEPATH.'libraries/'.$class.EXT);                        $is_subclass = FALSE;                }        }


I can't help you much with the testing, but I can help you extend the CI library.

You can create your own MY_Loader class inside /application/libraries/MY_Loader.php.

<?php  class MY_Loader extends CI_Loader {    function view($view, $vars = array(), $return = FALSE) {      echo 'My custom code goes here';    }  }

CodeIgniter will see this automatically. Just put in the functions you want to replace in the original library. Everything else will use the original.

For more info check out the CI manual page for creating core system classes.