lundi 16 septembre 2019

Why do factories not load column defaults?

I can't seem to find much on this topic as to why factories do not inherit database default values. Any insight would be helpful, as I'm currently redefining all column defaults in my factory in order to see them in my tests.

For example, here's an issue where I need the column to be loaded as I'm checking for it, but in my test, it's not being loaded until later.

TABLE: someTbl

id => int, auto increment
active => int, default 1
title => string,
description => text

FACTORY:

$factory->define(someTbl::class, function (Faker $faker) {
  return [
    'title' => 'Some title',
    'Description' => 'Some description'
  ];
});

MODEL:

class someTbl extends Model {
  public function isActive() {
    return $this->active === 1;
  }

  public function setActive() {
    $this->update(['active' => true]);
  }

  public function doSomething() {
    if(!$this->isActive()) throw new someRowNotActiveException();

    /** do something else if active **/
  }
}

TEST:

/** @test */
function user_can_do_something_with_function() {
  $foo = factory(someTbl::class)->create();
  $foo->doSomething(); // throws someRowNotActiveException();
}


I can get the test to pass if I do one of the following...

1) In my factory, define 'active' => true, or

2) In my test, before $foo->doSomething(), I call $foo->setActive()

Both of the above steps seems redundant because I feel like in the real world, when the model is created, it should return default column values that are defined on the database layer and not defined explicitly when the model was created.

Am I missing something here? I know this is happening on both Laravel 5 and 6.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire