laravel / framework

The Laravel Framework.
https://laravel.com
MIT License
32.21k stars 10.9k forks source link

Bug while fetching created models in testing #31824

Closed kikky7 closed 4 years ago

kikky7 commented 4 years ago

Description:

Can't get model in testing with create method.

Steps To Reproduce:

$ad = Ad::create([
    'title' => 'This is first ad',
    'body' => '',
]);

$this->assertDatabaseHas('ads', [
    'title' => 'This is first ad',
]);

dump($ad->title);
dump(get_class($ad));
dump(is_null(Ad::first()));

$ad2 = factory(Ad::class)->create();

dump($ad2->title);
dump(get_class($ad2));
dump(is_null(Ad::first()));

$user = User::create([
    'email' => 'test@example.com',
    'password' => 'secret',
    'type' => 'company',
]);

dump($user->email);
dump(get_class($user));
dump(is_null(User::where('email', 'test@example.com')->first()));

This is response:

"This is first ad"
"App\Ad"
true
"Automated optimal capacity"
"App\Ad"
false
"test@example.com"
"App\User"
false

Why first created Ad can't be fetched with Ad::first() or Ad::where('title', 'This is my first ad')->first()? It is always null...

Data is saved in database, which is confirmed with this line of code: $this->assertDatabaseHas('ads', [ 'title' => 'This is first ad', ]);

It only happens with this model (Ad); as you can see User works as expected, same as any other custom model I tried.

staudenmeir commented 4 years ago

What do the Ad model and its factory look like?

What's the result of dd($ad->getAttributes(), \DB::table('ads')->get());

kikky7 commented 4 years ago

Found bug, it's my mistake. I have global scope which filters them by is_preview. Thank you! I would never find it without posting database dump here.