Model boot() being ignore when updating model
Closed this issue · 2 comments
I'm using Codeception to test a user repository I'm building. I'm having an issue with one of my tests:
// DbUserRepositoryTest
public function testSetPassword()
{
$user = Factory::create("App\Models\User");
$user = $this->repo->setPassword($user, "randompassword");
$this->assertTrue(Hash::check("randompassword", $user->password));
}
// DbUserRepository
public function setPassword(User $user, $password)
{
$user->password = $password;
$user->password_confirmation = $password;
$user->save();
return $user;
}
I have a base model that validates the attributes on save. If the password and password_confirmation pass validate I unset the password_confirmation attribute so that that system doesn't try and save it to the database (obviously there is no password_confirmation column, it's just used for validation).
Creating a little test route returns the results I expect:
Route::get('testing', function() {
$repo = App::make("App\Repositories\Users\UserRepositoryInterface");
$user = App\Models\User::find(5712);
$user = $repo->setPassword($user, "randompassword");
dd(Hash::check("randompassword", $user->password)); // True
});
However my test fails. I get this error:
[PHPUnit_Framework_ExceptionWrapper] SQLSTATE[HY000]: General error: 1 no such column: password_confirmation (SQL: update "users" set "password" = randompassword, "password_confirmation" = randompassword, "updated_at" = 2014-11-13 11:42:01 where "id" = 1)
From what I can tell the validation method in my base model and static::saving function that runs it aren't firing at all when I run my test.
Is TestDummy not extending the models it's faking? Does anyone have any idea how I can resolve this issue?
We see a similar issue.
We use a static::creating boot method in some models to automatically generate a 16-character random id ("uid"). These are correctly generated when using Factory::create() during the first test method on an integration test, but they are ignored on Factory::create() calls in subsequent test methods in the same integration test. The static::creating method simply isn't being called.
We were able to get around this by simply faking the uid column in the factory declarations.
So perhaps this has nothing to do with TestDummy, but instead is a Codeception/Laravel4 issue.
There appears to be a decent explanation of the issue and an interesting solution here:
I was able to resolve the problem by simply calling the 'boot' method for all affected models in the _before() method for my Codeception test. Example:
protected function _before() {
Namespaced\Path\To\Model1::boot();
Namespaced\Path\To\Model2::boot();
}