Null values in FactoryMuffin define

292 views Asked by At

I am using PhPUnit, FactoryMuffin and Faker for testing in Laravel, with a PostgreSQL db. In the previous version of FactoryMuffin (Zizaco\FactoryMuff) I could assign null values to columns both in the static factory array and when calling FactoryMuff::create.

However this no longer works - if I use the following define:

FactoryMuffin::define('MyModel', array(
    'name' => 'word',
    'empty' => null,
    'another' => 'word'
));

when I call FactoryMuffin::create instead of passing NULL to the SQL INSERT statement it leaves the value blank, so I get:

INSERT INTO my_table ("name", "empty", "another") VALUES ('Ralph', , 'Someone');

which PGSQL doesn't allow. The same thing happens using

FactoryMuffin::create('MyModel', array('empty' => null));

Any ideas how to get round this, beyond instantiating the model and then assigning null to the field?

1

There are 1 answers

1
marcanuy On BEST ANSWER

Since FactoryMuffin 2.1 (and 3.*) you can take advantage of the callback functionality, e.g.:

FactoryMuffin::define('MyModel', array(
  'name' => 'word',
  'empty' => null,
  'another' => 'word'
))->setCallback(function ($object, $saved) {
  $object->empty = null;
});

In FactoryMuffin 2.1 the callback is set as the third parameter of the define:

FactoryMuffin::define('MyModel', array(
  'name' => 'word',
  'empty' => null,
  'another' => 'word'
), function ($object, $saved) {
  $object->empty = null;
});