phpunit-testingauthorizationcakephp-1.3simpletest

cakephp controller testing - how to test actions which require authorization?


The title pretty much says it all. I would like to test e.g. UsersController::admin_index() action, but it's required for the user to be authorized to access this location, therefore when I run the test it sends me to the login page and even when I log in manully, no tests are done.

So how can I force cake to skip authorization without editing the actual authorization code?

btw, in case it helps, my testAdminIndex() code looks like this:

function testAdminIndex() {     
    $result = $this->testAction('/admin/users/index');      
    debug($result); 
}

Solution

  • There's an article that covers the subject here ...

    http://mark-story.com/posts/view/testing-cakephp-controllers-the-hard-way

    The recommendation is to bypass "testAction" completely and manually perform the request, after adding session values for the authenticated user. The example is as follows ...

    function testAdminEdit() {
        $this->Posts->Session->write('Auth.User', array(
            'id' => 1,
            'username' => 'markstory',
        ));
        $this->Posts->data = array(
            'Post' => array(
                'id' => 2,
                'title' => 'Best article Evar!',
                'body' => 'some text',
            ),
            'Tag' => array(
                'Tag' => array(1,2,3),
            )
        );
        $this->Posts->params = Router::parse('/admin/posts/edit/2');
        $this->Posts->beforeFilter();
        $this->Posts->Component->startup($this->Posts);
        $this->Posts->admin_edit();
    }