farshadf's avatar

simple test in laravel in create method

i want to simply test my model to see if it can be created or not here is what i tried :

    public function it_test_insert_model(){
//        $this->actingAs(User::class);
        $wish = factory(Model::class)->create();
        $this->post('/model/create',$wish->toArray());
        $this->assertEquals(1,Model::all()->count());
    }

now my problem is every time it fails because it should equal the the numbers of models i have in my table . is there any way to just create one and test if it was created and then remove it ??? because now every time it remains in database . i just want to test if the model is able to be created or not . thanks

0 likes
8 replies
ksparkar's avatar

In this instance you should use

$wish = factory(Model::class)->make();

make() does not persist the model in the DB while create() does

tykus's avatar

You can use the factory's raw method to give you the array directly - you will not have even a Model instance in memory:

    public function it_test_insert_model(){
        $this->post('/model/create', factory(Model::class)->raw());
        $this->assertEquals(1,Model::count());
    }

Finally, count() is a Builder method too...

farshadf's avatar

now it gives me this error

Failed asserting that 0 matches expected 1.

if i change it to 0 it works well

tykus's avatar

if i change it to 0 it works well

Well, that's hardly a valid test outcome, is it?

Sanity check... is /model/create the correct endpoint for storing a new resource?

farshadf's avatar

yes it is do you mean is that the problem with making the model ???

tykus's avatar
tykus
Best Answer
Level 104

I don't know. For some reason, the record is not being created, I was wanted to know that the request was being made to the correct endpoint.

Can you dump the response:

    public function it_test_insert_model(){
        $this->post('/model/create', factory(Model::class)->raw())
        ->dump();
        $this->assertEquals(1,Model::count());
    }

See if there is some exception output; and if there is, turn off exception handling to see the nature of the exception:

    public function it_test_insert_model(){
    $this->withoutExceptionHandling();

        $this->post('/model/create', factory(Model::class)->raw());
        $this->assertEquals(1,Model::count());
    }
farshadf's avatar

This is the result of dump but i have the factory for it i am sure

) Tests\Feature\ModelTest::it_test_insert_model InvalidArgumentException: Unable to locate factory with name [default] [Tests\Feature\Model].

tykus's avatar

Is your Model class literally called Model, I thought that was a placeholder!?!?

Anyway the reason for the exception is you haven't namespaced the Model class:

// at the top of the test class
use App\Model;

or

// inline wherever you use the clasee
factory(\App\Model::class)->raw()

Please or to participate in this conversation.