diff --git a/tests/Database/DatabaseEloquentAppTest.php b/tests/Database/DatabaseEloquentAppTest.php new file mode 100644 index 000000000000..ea97de1f0722 --- /dev/null +++ b/tests/Database/DatabaseEloquentAppTest.php @@ -0,0 +1,100 @@ +id(); + $table->string('email')->unique(); + $table->timestamps(); + }); + } + + public function testObserverIsCalledOnTestsWithAfterCommit() + { + DatabaseEloquentAppTestUser::observe($observer = DatabaseEloquentAppTestUserObserver::resetting()); + + $user1 = DatabaseEloquentAppTestUser::create([ + 'email' => 'hello@example.com', + ]); + + $this->assertTrue($user1->exists); + $this->assertEquals(1, $observer::$calledTimes, 'Failed to assert the observer was called once.'); + } + + public function testObserverCalledWithAfterCommitWhenInsideTransaction() + { + DatabaseEloquentAppTestUser::observe($observer = DatabaseEloquentAppTestUserObserver::resetting()); + + $user1 = DB::transaction(fn () => DatabaseEloquentAppTestUser::create([ + 'email' => 'hello@example.com', + ])); + + $this->assertTrue($user1->exists); + $this->assertEquals(1, $observer::$calledTimes, 'Failed to assert the observer was called once.'); + } + + public function testObserverIsCalledOnTestsWithAfterCommitWhenUsingSavepoint() + { + DatabaseEloquentAppTestUser::observe($observer = DatabaseEloquentAppTestUserObserver::resetting()); + + $user1 = DatabaseEloquentAppTestUser::createOrFirst([ + 'email' => 'hello@example.com', + ]); + + $this->assertTrue($user1->exists); + $this->assertEquals(1, $observer::$calledTimes, 'Failed to assert the observer was called once.'); + } + + public function testObserverIsCalledOnTestsWithAfterCommitWhenUsingSavepointAndInsideTransaction() + { + DatabaseEloquentAppTestUser::observe($observer = DatabaseEloquentAppTestUserObserver::resetting()); + + $user1 = DB::transaction(fn () => DatabaseEloquentAppTestUser::createOrFirst([ + 'email' => 'hello@example.com', + ])); + + $this->assertTrue($user1->exists); + $this->assertEquals(1, $observer::$calledTimes, 'Failed to assert the observer was called once.'); + } +} + +class DatabaseEloquentAppTestUser extends Model +{ + protected $guarded = []; +} + +class DatabaseEloquentAppTestUserObserver +{ + public static $calledTimes = 0; + + public $afterCommit = true; + + public static function resetting() + { + static::$calledTimes = 0; + + return new static(); + } + + public function created($user) + { + static::$calledTimes++; + } +}