build in validation vs. unit testing

If You want to depend on build in model validation, You need to watch out on one pitfall

Let’s assume that there’s Stuff model with this validation:

$validate = array("name" => "notempty"); 

It works perfectly in web forms, but when You are making a unit test:

$this->assertFalse( $this->Stuff->save( array("id"=> 1) ) ); //test fail

Unfortunately it wont work, and the save operation will occur. Why?

Because that validation means that
If You have “name” element in saving array, it will be checked if it’s not empty (not null, nor false or “”)

So, if You need the test to pass, You can do this:

$this->assertFalse( $this->Stuff->save( array("id"=> 1, "name"=>"") ) ); // test passed

Or fix the validation rule like below:

$validate = array("name" => array("rule" =>"notempty", "required"=> true),

In that case model will check if this element even exists in saving array (and if its not empty)

We spent about 30mins. wandering why validation works through form, and not working in unit test.

Hope that was helpful :)

Share Button

Leave a Reply

Your email address will not be published. Required fields are marked *