6 months ago

Problem creating factory from a Model with custom constructor

Posted 6 months ago by dani94

Im created few unit testing, they works! But after refactor my Order Model creating custom constructor.

This is my Order Model constructor:

public function __construct()
    $this->status()->associate(OrderStatus::PENDINGACCEPTANCE); // this is 1

My factory class:

$factory->define(App\Order::class, function (Faker $faker) {
    return [
        'user_id' => function () {
            return factory(App\User::class)->create()->id;
        'order_status_id' => function () {
            return factory(App\OrderStatus::class)->create()->id;
        'cart_id' => function () {
            return factory(App\Cart::class)->create()->id;


And once simple example test

public function test_order_has_correct_price_whit_not_disscount()
        $products = factory(Product::class, 10)->create();
        $order = factory(Order::class)->create();

        $expectedPrice = 0.00;

        foreach ($products as $product) {
            $this->cartAction->addProducts($product->id, $order->cart);
            $expectedPrice += $product->currentPrice();

        $this->assertEquals($expectedPrice, $order->cart->price());

If I try to create order factory instance I get error. "I can understand auth error", but i tried with out this line $this->user()->associate(Auth::user()->id); and still error cause status asosation. Maybe factory create empty object then set attributes? I have no idea how to solve this... Any idea? Thanks guys!

Please sign in or create an account to participate in this conversation.