- Notifications
You must be signed in to change notification settings - Fork23
A test suite for Buffalo applications
License
gobuffalo/suite
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
Suite is a package meant to make testinggobuffalo.io applications easier.
This is the entry point into your unit testing suite. TheTest_ActionSuite(t *testing.T)
function iscompatible with thego test
command, and it should:
- Create and configure your new test suite instance (
ActionSuite
in this case) - Call
suite.Run
with the*testing.T
passed by the Go testing system, and your newActionSuite
instance
package actions_testimport ("testing""github.com/gobuffalo/suite/v4""github.com/gobuffalo/toodo/actions")typeActionSuitestruct {*suite.Action}funcTest_ActionSuite(t*testing.T) {as:=&ActionSuite{suite.NewAction(actions.App())}suite.Run(t,as)}
This is where you write your actual test logic. The rules for test names are similar, but not the same, as withgo test
:
- Each test is a method on your
*ActionSuite
- Test method names should start with
Test
(note the upper caseT
) - Test methods should have no arguments
A few additional notes:
- To avoid race conditions on the testing database, always use the
ActionSuite
variable calledDB
to access the database (not your production app's database) - You can access the raw
*testing.T
value if needed withas.T()
ActionSuite
has support fortestify
'srequire
package andassert
package- ... So try to use one of those instead packages of using the raw methods on the
*testing.T
- The default database that
suite
will connect to is calledtesting
in yourdatabase.yml
package actions_testimport ("fmt""github.com/gobuffalo/toodo/models")func (as*ActionSuite)Test_TodosResource_List() {todos:= models.Todos{ {Title:"buy milk"}, {Title:"read a good book"}, }for_,t:=rangetodos {err:=as.DB.Create(&t)as.NoError(err) }res:=as.HTML("/todos").Get()body:=res.Body.String()for_,t:=rangetodos {as.Contains(body,fmt.Sprintf("<h2>%s</h2>",t.Title)) }}func (as*ActionSuite)Test_TodosResource_New() {res:=as.HTML("/todos/new").Get()as.Contains(res.Body.String(),"<h1>New Todo</h1>")}func (as*ActionSuite)Test_TodosResource_Create() {todo:=&models.Todo{Title:"Learn Go"}res:=as.HTML("/todos").Post(todo)as.Equal(301,res.Code)as.Equal("/todos",res.Location())err:=as.DB.First(todo)as.NoError(err)as.NotZero(todo.ID)as.NotZero(todo.CreatedAt)as.Equal("Learn Go",todo.Title)}func (as*ActionSuite)Test_TodosResource_Create_Errors() {todo:=&models.Todo{}res:=as.HTML("/todos").Post(todo)as.Equal(422,res.Code)as.Contains(res.Body.String(),"Title can not be blank.")c,err:=as.DB.Count(todo)as.NoError(err)as.Equal(0,c)}func (as*ActionSuite)Test_TodosResource_Update() {todo:=&models.Todo{Title:"Lern Go"}verrs,err:=as.DB.ValidateAndCreate(todo)as.NoError(err)as.False(verrs.HasAny())res:=as.HTML("/todos/%s",todo.ID).Put(&models.Todo{ID:todo.ID,Title:"Learn Go"})as.Equal(200,res.Code)err=as.DB.Reload(todo)as.NoError(err)as.Equal("Learn Go",todo.Title)}
Often it is useful to load a series of data into the database at the start of the test to make testing easier. For example, you need to have a user in the database to log a person into the application, or you need some data in the database to test destroying that data. Fixtures let us solve these problems easily.
First you need to setup your test suite to use fixtures. You can do this by usingsuite.NewActionWithFixtures
orsuite.NewModelWithFixtures
methods to create new test suites that take anfs.FS
pointing to where the files for this suite live.
package actionsimport ("os""testing""github.com/gobuffalo/suite/v4")typeActionSuitestruct {*suite.Action}funcTest_ActionSuite(t*testing.T) {action,err:=suite.NewActionWithFixtures(App(),os.DirFS("../fixtures"))iferr!=nil {t.Fatal(err) }as:=&ActionSuite{Action:action, }suite.Run(t,as)}
Once your suite is set up, you can createN
numbers of*.toml
files in the directory you've chosen for your fixtures, in this example,../fixtures
.
[[scenario]]name ="lots of widgets" [[scenario.table]]name ="widgets" [[scenario.table.row]]id ="<%= uuidNamed("widget") %>"name ="This is widget #1"body ="some widget body"created_at ="<%= now() %>"updated_at ="<%= now() %>" [[scenario.table.row]]id ="<%= uuid() %>"name ="This is widget #2"body ="some widget body"created_at ="<%= now() %>"updated_at ="<%= now() %>" [[scenario.table]]name ="users" [[scenario.table.row]]id ="<%= uuid() %>"name ="Mark Bates"admin =trueprice =19.99widget_id ="<%= uuidNamed("widget") %>"created_at ="<%= now() %>"updated_at ="<%= now() %>"
The*.toml
files all get run throughhttps://github.com/gobuffalo/plush before they're decoded, so you can make use of the helpful helper methods that ship with Plush.
We've also add a couple of useful helpers for you as well:
uuid()
- returns a newgithub.com/gobuffalo/uuid.UUID
now()
- returnstime.Now()
nowAdd(s)
andnowSub(s)
- similar tonow()
buts
amount of seconds is added or substracted, respectively, from the return valueuuidNamed(name)
- will attempt to return a previously declared UUID with that name, useful, for relations/associations. If there was one that wasn't defined with that name, a new one will be created.hash(string, opts)
- will create the hashed value of the string (useful for creating a password), you can define the cost as an opts (the default isbcrypt.DefaultCost
)
In your suite tests you need to call theLoadFixture
method giving it the name of the fixtures you would like to use for this test.
func (as*ActionSuite)Test_WidgetsResource_List() {as.LoadFixture("lots of widgets")res:=as.HTML("/widgets").Get()body:=res.Body.String()as.Contains(body,"widget #1")as.Contains(body,"widget #2")}
- Can I call
LoadFixture
more than once in a test? - Absolutely! Call it as many times as you want! - Can I load multiple rows into a table in one scenario? - Absolutely!
- Can I load data into multiple tables in one scenario? - Absolutely!
- Will it load all my fixtures? - No, you have to load specific scenarios, so don't be afraid to create lots of scenarios and only call the ones you need per test.
- Will this pollute my database, and how do I clear data between tests? - No need to worry, the suite will truncate any data in your database between test runs, so you never have to worry about it.
About
A test suite for Buffalo applications