Farshad
Farshad

Reputation: 2000

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

Upvotes: 1

Views: 149

Answers (1)

mrhn
mrhn

Reputation: 18926

There is two approaches there is commonly used, you can either run migrations or database transactions to reset your database state. Migrations runs fairly slow if your application is big, transactions is way quicker and is my suggested approach.

Database migrations

use Illuminate\Foundation\Testing\DatabaseMigrations;

class YourTestClass {
    use DatabaseMigrations;

    public function it_test_insert_model() {
        ...
    }
}

Database transactions

use Illuminate\Foundation\Testing\DatabaseTransactions;

class YourTestClass {
    use DatabaseTransactions;

    public function it_test_insert_model() {
        ...
    }
}

Upvotes: 3

Related Questions