ChrisSFR's avatar

Why the Factory create id is 0 in test

I have an Item::class model factory, which sets the item_id and the name. Now I want to test, if an item is created. I know it is no convenient test. It is only for practice and get an understanding of how to test.

public function testCreateItem()
    {
        $item = factory(App\Item::class)->create([
            'item_id' => '1001',
            'name' => 'testitem'
            ]);
        $this->assertEquals('1001', $item->item_id);
        $this->assertEquals('testitem', $item->name);
    }

The assertEquals item_id fails with:

Failed asserting that '1001' matches expected 0.

I don't get, why the item_id is 0 . In my database it gets set right, when I comment

//use DatabaseTransactions;

Note: The item_id column in the database is a primary string.

0 likes
4 replies
ChrisSFR's avatar

Its just a small Model

namespace App;

use Illuminate\Database\Eloquent\Model;

class Item extends Model
{
    protected $primaryKey = 'item_id';
}

Schema:

`Schema::create('items', function (Blueprint $table) {
            $table->string('item_id')->primary();
            $table->string('name');
            $table->timestamps();
        });

When I do factorys()->make() instead of create. It works! But when I do a save() after the make() its 0 again.

ChrisSFR's avatar

The same with:

public function testCreateItem()
    {
        $item = new App\Item;
        $item->item_id = '1005';
        $item->name = 'testitem';
        $item->save();
        $this->assertEquals('1005', $item->item_id);
        $this->assertEquals('testitem', $item->name);
    }
ChrisSFR's avatar
ChrisSFR
OP
Best Answer
Level 10

Found the problem. It's because item_id is a string primaryKey with no auto-increment. a

public $incrementing = false; 

in App\Item solved the problem. Thanks goes to this post: http://stackoverflow.com/questions/25604605/laravel-eloquent-after-save-id-becomes-0

From old laravel documentation:

Note: Typically, your Eloquent models will have auto-incrementing keys. However, if you wish to specify your own keys, set the incrementing property on your model to false.
7 likes

Please or to participate in this conversation.