Model Factories
Factories generate fake data for tests and seeders. Define a factory once, then create single or multiple records with randomized or overridden attributes. Powered by the built-in database.Faker.
Defining a Factory
PostFactory := database.Define("posts", func(f *database.Faker) map[string]any {
return map[string]any{
"title": f.Sentence(),
"content": f.Paragraph(),
"status": "draft",
}
})
UserFactory := database.Define("users", func(f *database.Faker) map[string]any {
return map[string]any{
"name": f.Word() + " " + f.Word(),
"email": f.Email(),
"password": "$2a$10$...", // pre-hashed
"role": "user",
}
})
Faker Methods
| Method | Returns | Example |
|---|---|---|
Sentence() | string | "The quick brown fox jumps" |
Paragraph() | string | Multiple sentences |
Email() | string | "user42@example.com" |
Word() | string | "lorem" |
Int(min, max) | int | 42 |
Create Records
db := database.Get()
// Create a single record
PostFactory.Create(db)
// Create many records
PostFactory.CreateMany(db, 50)
Override Attributes (Merge)
// Override specific fields
PostFactory.Merge(map[string]any{
"status": "published",
"title": "Custom Title",
}).Create(db)
// Create published posts in bulk
PostFactory.Merge(map[string]any{"status": "published"}).CreateMany(db, 10)
Using in Seeders
package seeders
import (
"github.com/CodeSyncr/nimbus/lucid"
)
func SeedPosts(db *lucid.DB) {
// Create 5 users
UserFactory.CreateMany(db, 5)
// Create 20 draft posts
PostFactory.CreateMany(db, 20)
// Create 10 published posts
PostFactory.Merge(map[string]any{"status": "published"}).CreateMany(db, 10)
}
Using in Tests
func TestListPublishedPosts(t *testing.T) {
db := setupTestDB()
// Seed test data
PostFactory.Merge(map[string]any{"status": "published"}).CreateMany(db, 3)
PostFactory.Merge(map[string]any{"status": "draft"}).CreateMany(db, 2)
// Test
var published []Post
db.Where("status = ?", "published").Find(&published)
assert.Len(t, published, 3)
}