Rails style fixtures go testing with Gorm (ORM)

Introduction

Kyaw Myint Thein
2 min readJul 29, 2016

In this article, I want to introduce the Ruby on rails style fixture library gofixtures for Golang testing and how to use with Gorm ORM. The ideal of gofixtures is setup demo data for testing.

https://github.com/kyawmyintthein/gofixtures

There is no dependencies for database driver and ORM. gofixtures load yaml format file and parse that file to specific Golang’s Struct.

Usage

Before we start using gofixtures, we need to setup fixture folder path. Then, you need to load the specific yaml format fixture file. One file can have multiple objects. for example:

main.go

package tests
import(
"testings"
"github.com/kyawmyintthein/gofixtures"
)
func init(){
gofixtures.SetupConfig("data")
}
func TestLoadFixtureFile(t *testing.T){
fixture, err := gofixtures.LoadFixture("example")
if err != nil{
t.Errorf("failed to load fixture: %v", err)
}
}
func TestAddUser(t *testing.T){
fixture, err := gofixtures.LoadFixture("example")
if err != nil{
t.Errorf("failed to load fixture: %v", err)
}
user := models.User{}
err = fixture.Load("one",&user)
if err != nil{
t.Errorf("failed to load fixture model: %v", err)
}
v, err := models.AddUser(user)
if err != nil{
t.Errorf("failed to load fixture model: %v", err)
}
if v.Name == ""{
t.Errorf("failed to load fixture model")
}
}

user.go

package models
import(

)
type User struct{
Name string `json:"name"`
Age int64 `json:"age"`
}
func AddUser(m User) (User, error) {
var (
err error
)
if !db.Gorm().NewRecord(m) {
return m, errors.New("Primary key should empty.")
}
tx := db.Gorm().Begin()
if err = tx.Create(&m).Error; err != nil {
tx.Rollback()
return m, err
}
tx.Commit()
return m, err
}

First of all, gofixtures load the example.yaml as []byte array in fixture object. Currently, gofixtures support to parse single struct object from fixture content([]byte). You can load one object by using name of object. In yaml, you need to have specific format as follow:

data/example.yaml

one:  
name: John
age: 21
two:
name: Kyaw
age: 23

In above yaml file, you can load with “one” or “two” as object name. Parse yaml to struct object is the responsibilities of gofixtures.

--

--