popolo - code simple..

popolo - code simple..

Masonite Project - Factory Tinker Example Tutorial

Masonite Project - Factory Tinker Example Tutorial

Theodoros Kafantaris's photo
Theodoros Kafantaris
·May 6, 2022·

2 min read

Table of contents

  • Masonite Installation
  • Activating Our Virtual Environment
  • Install Masonite
  • Start project
  • Start Development Server
  • Add Dummy Users

In this series, we will see a Masonite factory tinker example.

As we know testing is very important part of any web development project. Sometime we may require to add hundreds records in our users table. Also think about if we require to check pagination. then we have to add some records for testing. So, we have 2 options.

  1. Add manually thousands of records
  2. Add them using factories. Factories are simple and easy ways to generate mass amounts of data quickly.

Let's see how to do it step by step below.

Masonite Installation

mkdir masonite-factories
cd masonite-factories

Activating Our Virtual Environment

python -m venv venv
source venv/bin/activate

Install Masonite

pip install masonite

Start project

project start .

Start Development Server

python craft serve

Add Dummy Users

Now, we need to run default migrations, so we have created new users table. So let's run migration command:

python craft migrate

We are using the default DB configuration that is coming with Masonite and it is sqlite.

Now we will create some users using the user factory.

We need to do the following steps:

1) In the config folder we are creating a new file with name config/factories.py.

2) In factories.py, we are putting the following configuration.

# config/factories.py
from masoniteorm import Factory
from app.models.User import User

def user_factory(faker):
    return {
        'name': faker.name(),
        'email': faker.email(),
        'password': 'secret'
    }

Factory.register(User, user_factory)

3) We connect to tinker

python craft tinker

4) We are executing the following commands:

from config.factories import Factory
users = Factory(User, 50).create()

That's it! We have now 50 users in our DB!

 
Share this