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.
- Add manually thousands of records
- 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!