jeudi 28 janvier 2016

Laravel, phpunit fails due to empty foreign key

I'm getting this error while running a phpunit test:

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'profile_id' cannot be null (SQL: insert into `comments` (`description`, `status`, `profile_id`, `project_id`, `updated_at`, `created_at`) values (Awesome Comment, active, , 21, 2016-01-29 00:05:21, 2016-01-29 00:05:21))

As you can see it is sending an empty id for the profile_id and I'm creating the profile before creating the comment. Here is the code of my test:

public function testProjectCommentCreation()
{
    $category = factory(\App\Category::class)->create();
    $category->projects()->save(factory(\App\Project::class)->make());


    $profile = factory(\App\Profile::class)->make([
        'name' => 'John',
        'last_name' => 'Snow',
        'skills' => 'php'
    ]);

    $category->projects[0]->comments()->save(factory(\App\Comment::class)->make([
        'description'=>'Awesome Comment',
        'status'=>'active',
        'profile_id'=>$profile->id
    ]));

    $this->post(route('api.projects.comments.store', ["projects" => $category->projects[0]->id]), $category->projects[0]->comments->jsonSerialize(), $this->jsonHeaders)
        ->seeInDatabase('comments', ['project_id' => $category->projects[0]->id])
        ->assertResponseOk();
}

A Project belongs to a Category and a Comment belongs to a Project and a Profile, so I need to send both foreign keys values profile_id and project_id, the problem is that I'm not sure how to retrieve the id of the profile I created.

These are the factories I use:

$factory->define(App\Profile::class, function (Faker\Generator $faker) {
return [
    'name' => $faker->name,
    'last_name' => $faker->name,
    'status' => 'active',
    'avatar' => str_random(10),
    'skills'=> str_random(10),
    'notifications'=>'on'
];
});

$factory->define(App\Comment::class, function (Faker\Generator $faker) {
return [
    'description' => str_random(10),
    'status' => 'active',
    'profile_id' => 1,
    'project_id' => 1
];});

$factory->define(App\Category::class, function (Faker\Generator $faker) {
return [
    'description' => str_random(10),
    'status' => 'active'
];});

$factory->define(App\Project::class, function (Faker\Generator $faker) {
return [
    'description' => str_random(10),
    'status' => 'active',
    'privacy' => 'false'
];});

I've tested the construction of each type of Object and it is working, what I'm failing is to create a Comment since I need to create a Profile first and retrieve the id and for some reason using $profile->id is pulling null



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1OT6UA6
via IFTTT

Aucun commentaire:

Enregistrer un commentaire