2

I am pulling order information from an external API and saving the entire JSON response into a documents table.

I obviously do not want to call this API when testing so I have setup a factory, but I am struggling with how to pull in these JSON stubs. For example:

// factory

$factory->define(App\OrderDocument::class, function (Faker $faker) {
    return [
        'document_id' => $faker->uuid,
        'status' => $faker->randomElement(['open', 'partial', 'processed', 'updating']),
        'document' => $faker->text
    ];
});

// Currently using it like...

foreach ($this->fullDocuments() as $id => $document){
    $a = factory(\App\OrderDocument::class)->create([
        'document_id' => $id,
        'status' => 'full'
    ]);
    $a->setRawAttributes(['document' => $document]);
    $a->save();
}

where $this->fullDocuments() contains an array of the document_id and raw JSON response from the API.

I know a better way to do this is to factory the entire JSON document. The JSON contains about 500 lines so it would be very time consuming but also I do not own this data, so I assume I should not be trying to fake it.

Within my test, I would prefer to do something like the below, but am not sure how.

factory(OrderDocument::class, 10)->create([
    'document_id' => $this->getDocumentId($i++),
    'document' => $this->getDocumentStub($i++),
]);
Adam Lambert
  • 1,311
  • 3
  • 24
  • 45
  • Hi Adam. You can save needed JSON to the directory with mocks, like a `{project_dir}/tests/Unit/Mocks/Api/response.json`, and read data from this file for creating documents. – Oleg Samorai Feb 20 '20 at 13:11
  • @OlegSamorai I have done this already. I just need a mechanism to get these files into the `document` field of my factory. I can used `file_get_contents` to retrieve the file, but I need to do something like `file_get_contents('file'.$i++)` from within the factory create method. – Adam Lambert Feb 22 '20 at 10:56
  • Can you use database seeder, instead of the factory, Or you need a list of created objects into your test? – Oleg Samorai Feb 24 '20 at 09:32

0 Answers0