Skip to content

Instantly share code, notes, and snippets.

@bluele
Created July 31, 2016 09:41
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bluele/7babe26567785a198bb0bd813543ca86 to your computer and use it in GitHub Desktop.
Save bluele/7babe26567785a198bb0bd813543ca86 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"time"
"github.com/bluele/factory-go/factory"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/sqlite"
)
type User struct {
ID int `gorm:"primary_key"`
Name string
}
func (user *User) Save(db *gorm.DB) error {
return db.Create(user).Error
}
var UserFactory = factory.NewFactory(
&User{},
).SeqInt("ID", func(n int) (interface{}, error) {
return n + int(time.Now().Unix()), nil
}).Attr("Name", func(args factory.Args) (interface{}, error) {
user := args.Instance().(*User)
return fmt.Sprintf("user-%d", user.ID), nil
})
func main() {
db, err := gorm.Open("sqlite3", "test.db")
if err != nil {
panic("failed to connect database")
}
db.LogMode(true)
db.AutoMigrate(&User{})
for i := 0; i < 3; i++ {
user := UserFactory.MustCreate().(*User)
if err := user.Save(db); err != nil {
panic(err)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment