Redirecting in CodeIgniter 2 with PHPUnit and CIUnit

I am using PHPUnit 3.5 and CIUnit with PHING 2.4 to unit test CodeIgniter controller functions

The problem is when the function under test contains a redirect () function, the test test stops and won't continue executing. There is no error log available for this either.

What could be the problem for this? Do I need to download / update a specific PHPUnit library?

Any suggestion would be greatly appreciated.

thank

+3


source to share


2 answers


Well, that would be because redirect()

fn exits after doing a redirect (this is what you should do when doing a redirect to stop further code execution while waiting for a browser redirect).

/system/helpers/url_helper.php:

/**
 * Header Redirect
 *
 * Header redirect in two flavors
 * For very fine grained control over headers, you could use the Output
 * Library set_header() function.
 *
 * @access  public
 * @param   string  the URL
 * @param   string  the method: location or redirect
 * @return  string
 */
if ( ! function_exists('redirect'))
{
    function redirect($uri = '', $method = 'location', $http_response_code = 302)
    {
        if ( ! preg_match('#^https?://#i', $uri))
        {
            $uri = site_url($uri);
        }

        switch($method)
        {
            case 'refresh'  : header("Refresh:0;url=".$uri);
                break;
            default         : header("Location: ".$uri, TRUE, $http_response_code);
                break;
        }
        exit;  <===<<< here is the exit
    }
}

      



The only way around this is to fix it exit;

after the redirect.

Link: http://codeigniter.com/user_guide/helpers/url_helper.html

+1


source


I ran into this too. I needed to check that a certain function is being redirected. I just argued that the new redirect url ends with a specific line:

#Calling the controller method    
$this->ci->register();
#output the headers
$out = $this->ci->ouput->get_headers();
#check that the uri ends with where it is redirecting
$this->assertStringEndsWith('/user', (string)$out[0][0]);

      



Keep in mind that unit tests are for a specific method only. If you need to test multiple redirects to different controllers / methods using something like selenium and also unit tests for each individual method.

+1


source







All Articles