Laravel-Model-Validation icon indicating copy to clipboard operation
Laravel-Model-Validation copied to clipboard

$model->validate() reports correctly, but $model->save() does not

Open felixkiss opened this issue 11 years ago • 5 comments

Basic Model validation, 2 tests defined:

public function testShouldBeInvalidWithoutUsername()
{
    $user = Factory::user();
    $user->username = null;

    Should::beFalse($user->validate(), 'User should be invalid without username');
}

public function testShouldPreventFromSavingWithoutUsername()
{
    $user = Factory::user();
    $user->username = null;

    Should::beFalse($user->save(), 'User should not be saved without username');
}

User model:

class User extends Model
{
    protected static $rules = array(
        'username' => 'required',
    );
}

First test passes, second does not. Seems odd to me, because save() does directly react to the return value of validate().

What am I doing wrong?

felixkiss avatar Jun 04 '13 10:06 felixkiss

Are you hooking into the save() method somehow? By default, Laravel doesn't auto-validate.

JeffreyWay avatar Jun 04 '13 20:06 JeffreyWay

I'm confused, this is what this package is supposed to do, isn't it?

simply save the model as you normally would, and let the package worry about the validation. If it fails, then the model's save method will return false.

Doesn't Way\Database\Model hook into save()? https://github.com/JeffreyWay/Laravel-Model-Validation/blob/437cf1e06c39046ce3a4a7394097ac5dc9e02d0c/src/Way/Database/Model.php#L43

felixkiss avatar Jun 05 '13 07:06 felixkiss

I'm sorry. I thought you were commenting in a different project entirely. I'll take a look. :)

JeffreyWay avatar Jun 05 '13 15:06 JeffreyWay

Is this still an issue? I believe I'm running into the same thing.

bmitch avatar Aug 13 '13 22:08 bmitch

For me, this tests are successful, if I extend my Test class from PHPUnit_Framework_TestCase, but go wrong if I extend from TestCase (included into the framework).

I couldn't figure out why, but opted to extend PHPUnit_Framework_TestCase in model tests.

Issue is still active, because what if I want to use the nice helper methods for controller testing, etc. defined in Illuminate\Foundation\Testing\TestCase?

felixkiss avatar Aug 16 '13 07:08 felixkiss