开发者

CakePHP - Unit testing validation not called

开发者 https://www.devze.com 2023-03-06 00:25 出处:网络
I\'m doing some unit testing but having issues with Model validation not getting called. Here is what I have in the Fixture.

I'm doing some unit testing but having issues with Model validation not getting called.

Here is what I have in the Fixture.

<?php
    class ItemFixture extends CakeTestFixture {
    var $name = 'Item';
    var $import = array(
            'model' => 'Item',
            'table' => 'items'
    );

    var $records = array(array(
            'id' => 1,
            'title' => 'Title2',
            'year' => '1992'
            ),array(
            'id' => 2,
            'title' => 'Lorem ipsum dolor sit amet',
            'year' => '1995'
            ));
    }

?>

Here is what I have in the model unit test

    <?php

    App::import('Model', 'Item');

    class ItemTest extends Item {
            var $name = 'ItemTest';
            var $useTable = 'items';
            var $useDbConfig = 'test';
    }

    class ItemTestCase extends CakeTestCase {
            var $fixtures = array('app.item');

            function startTest() {
                    $this->ItemTest =& ClassRegistry::init('ItemTest');
            }

            function testAdd() {
                    $data = array(
                    'ItemTest' => array(
                    'title' => 'Best article Evar!'
                    )
                    );

                    $result = $this->ItemTest->saveAll($data);
            }

            function endTest() {

    }

}

?>

And here is the validation that I have in the actual Model.

    'year' => array(
            'numeric' => array(
            'rule' => 'numeric',
            'allowEmpty' => false,
            'message' => 'Numbers only'
    ),
    'minLength' => array(
            'rule' => array('minLength', 4),
            'message' => 'Year in YYYY format'
    ),
    'maxLength' => array(
            'rule' => array('maxLength', 4),
            'message' => 'Year in YYYY format'
    )

See, in testAdd, I'm not passing year which is not supposed to be empty, but it actually passed. Why开发者_如何学编程 isn't the validation getting called?

Thank you,

Tee


allowEmpty only works if the data contains the specified field, in your case year. To make the validation fail you either have to add 'year' => '' to your $data array in testAdd or add 'required' => true to your validation rule to enforce there is a year field in the data.

See also http://book.cakephp.org/view/1148/allowEmpty

0

精彩评论

暂无评论...
验证码 换一张
取 消