README.md
1[![CircleCI](https://circleci.com/gh/cucumber/godog/tree/master.svg?style=svg)](https://circleci.com/gh/cucumber/godog/tree/master)
2[![GoDoc](https://godoc.org/github.com/cucumber/godog?status.svg)](https://godoc.org/github.com/cucumber/godog)
3[![codecov](https://codecov.io/gh/cucumber/godog/branch/master/graph/badge.svg)](https://codecov.io/gh/cucumber/godog)
4
5# Godog
6
7<p align="center"><img src="/logo.png" alt="Godog logo" style="width:250px;" /></p>
8
9**The API is likely to change a few times before we reach 1.0.0**
10
11Please read all the README, you may find it very useful. And do not forget
12to peek into the
13[CHANGELOG](https://github.com/cucumber/godog/blob/master/CHANGELOG.md)
14from time to time.
15
16Package godog is the official Cucumber BDD framework for Golang, it merges
17specification and test documentation into one cohesive whole. The author
18is a member of [cucumber team](https://github.com/cucumber).
19
20The project is inspired by [behat][behat] and [cucumber][cucumber] and is
21based on cucumber [gherkin3 parser][gherkin].
22
23**Godog** does not intervene with the standard **go test** command
24behavior. You can leverage both frameworks to functionally test your
25application while maintaining all test related source code in **_test.go**
26files.
27
28**Godog** acts similar compared to **go test** command, by using go
29compiler and linker tool in order to produce test executable. Godog
30contexts need to be exported the same way as **Test** functions for go
31tests. Note, that if you use **godog** command tool, it will use `go`
32executable to determine compiler and linker.
33
34**Godog** depends on [gherkin-go](https://github.com/cucumber/gherkin-go) and [messages-go](https://github.com/cucumber/messages-go).
35
36The following about section was taken from
37[cucumber](https://cucumber.io/) homepage.
38
39## Notice:
40
41**If your project depend on the master version of godog instead of a specific release, please read this.**
42
43Due to dependency changes in a coming merge to master, including breaking changes, you should update how you install or depend on godog so that you have a version specified.
44
45### Install
46```
47go get github.com/cucumber/godog/cmd/godog@v0.8.1
48```
49Adding `@v0.8.1` will install v0.8.1 specifically instead of master.
50
51Running `within the $GOPATH`, you would also need to set `GO111MODULE=on`, like this:
52```
53GO111MODULE=on go get github.com/cucumber/godog/cmd/godog@v0.8.1
54```
55
56## About
57
58#### A single source of truth
59
60Cucumber merges specification and test documentation into one cohesive whole.
61
62#### Living documentation
63
64Because they're automatically tested by Cucumber, your specifications are
65always bang up-to-date.
66
67#### Focus on the customer
68
69Business and IT don't always understand each other. Cucumber's executable
70specifications encourage closer collaboration, helping teams keep the
71business goal in mind at all times.
72
73#### Less rework
74
75When automated testing is this much fun, teams can easily protect
76themselves from costly regressions.
77
78## Install
79```
80go get github.com/cucumber/godog/cmd/godog@v0.9.0
81```
82Adding `@v0.9.0` will install v0.9.0 specifically instead of master.
83
84Running `within the $GOPATH`, you would also need to set `GO111MODULE=on`, like this:
85```
86GO111MODULE=on go get github.com/cucumber/godog/cmd/godog@v0.9.0
87```
88
89## Example
90
91The following example can be [found
92here](/_examples/godogs).
93
94### Step 1
95
96Given we create a new go package **$GOPATH/src/godogs**. From now on, this
97is our work directory `cd $GOPATH/src/godogs`.
98
99Imagine we have a **godog cart** to serve godogs for lunch. First of all,
100we describe our feature in plain text - `vim
101$GOPATH/src/godogs/features/godogs.feature`:
102
103``` gherkin
104# file: $GOPATH/src/godogs/features/godogs.feature
105Feature: eat godogs
106 In order to be happy
107 As a hungry gopher
108 I need to be able to eat godogs
109
110 Scenario: Eat 5 out of 12
111 Given there are 12 godogs
112 When I eat 5
113 Then there should be 7 remaining
114```
115
116**NOTE:** same as **go test** godog respects package level isolation. All
117your step definitions should be in your tested package root directory. In
118this case - `$GOPATH/src/godogs`
119
120### Step 2
121
122If godog is installed in your GOPATH. We can run `godog` inside the
123**$GOPATH/src/godogs** directory. You should see that the steps are
124undefined:
125
126![Undefined step snippets](/screenshots/undefined.png?raw=true)
127
128If we wish to vendor godog dependency, we can do it as usual, using tools
129you prefer:
130
131 git clone https://github.com/cucumber/godog.git $GOPATH/src/godogs/vendor/github.com/cucumber/godog
132
133It gives you undefined step snippets to implement in your test context.
134You may copy these snippets into your `godogs_test.go` file.
135
136Our directory structure should now look like:
137
138![Directory layout](/screenshots/dir-tree.png?raw=true)
139
140If you copy the snippets into our test file and run godog again. We should
141see the step definition is now pending:
142
143![Pending step definition](/screenshots/pending.png?raw=true)
144
145You may change **ErrPending** to **nil** and the scenario will
146pass successfully.
147
148Since we need a working implementation, we may start by implementing only what is necessary.
149
150### Step 3
151
152We only need a number of **godogs** for now. Lets keep it simple.
153
154``` go
155/* file: $GOPATH/src/godogs/godogs.go */
156package main
157
158// Godogs available to eat
159var Godogs int
160
161func main() { /* usual main func */ }
162```
163
164### Step 4
165
166Now lets implement our step definitions, which we can copy from generated
167console output snippets in order to test our feature requirements:
168
169``` go
170/* file: $GOPATH/src/godogs/godogs_test.go */
171package main
172
173import (
174 "fmt"
175
176 "github.com/cucumber/godog"
177 messages "github.com/cucumber/messages-go/v10"
178)
179
180func thereAreGodogs(available int) error {
181 Godogs = available
182 return nil
183}
184
185func iEat(num int) error {
186 if Godogs < num {
187 return fmt.Errorf("you cannot eat %d godogs, there are %d available", num, Godogs)
188 }
189 Godogs -= num
190 return nil
191}
192
193func thereShouldBeRemaining(remaining int) error {
194 if Godogs != remaining {
195 return fmt.Errorf("expected %d godogs to be remaining, but there is %d", remaining, Godogs)
196 }
197 return nil
198}
199
200func FeatureContext(s *godog.Suite) {
201 s.Step(`^there are (\d+) godogs$`, thereAreGodogs)
202 s.Step(`^I eat (\d+)$`, iEat)
203 s.Step(`^there should be (\d+) remaining$`, thereShouldBeRemaining)
204
205 s.BeforeScenario(func(*messages.Pickle) {
206 Godogs = 0 // clean the state before every scenario
207 })
208}
209```
210
211Now when you run the `godog` again, you should see:
212
213![Passed suite](/screenshots/passed.png?raw=true)
214
215We have hooked to **BeforeScenario** event in order to reset application
216state before each scenario. You may hook into more events, like
217**AfterStep** to print all state in case of an error. Or
218**BeforeSuite** to prepare a database.
219
220By now, you should have figured out, how to use **godog**. Another advice
221is to make steps orthogonal, small and simple to read for a user. Whether
222the user is a dumb website user or an API developer, who may understand
223a little more technical context - it should target that user.
224
225When steps are orthogonal and small, you can combine them just like you do
226with Unix tools. Look how to simplify or remove ones, which can be
227composed.
228
229### References and Tutorials
230
231- [cucumber-html-reporter](https://github.com/gkushang/cucumber-html-reporter)
232 may be used in order to generate **html** reports together with
233 **cucumber** output formatter. See the [following docker
234 image](https://github.com/myie/cucumber-html-reporter) for usage
235 details.
236- [how to use godog by semaphoreci](https://semaphoreci.com/community/tutorials/how-to-use-godog-for-behavior-driven-development-in-go)
237- see [examples](https://github.com/cucumber/godog/tree/master/_examples)
238- see extension [AssistDog](https://github.com/hellomd/assistdog), which
239 may have useful **gherkin.DataTable** transformations or comparison
240 methods for assertions.
241
242### Documentation
243
244See [godoc][godoc] for general API details.
245See **[Circle Config](/.circleci/config.yml)** for supported **go** versions.
246See `godog -h` for general command options.
247
248See implementation examples:
249
250- [rest API server](/_examples/api)
251- [rest API with Database](/_examples/db)
252- [godogs](/_examples/godogs)
253
254## FAQ
255
256### Running Godog with go test
257
258You may integrate running **godog** in your **go test** command. You can
259run it using go [TestMain](https://golang.org/pkg/testing/#hdr-Main) func
260available since **go 1.4**. In this case it is not necessary to have
261**godog** command installed. See the following examples.
262
263The following example binds **godog** flags with specified prefix `godog`
264in order to prevent flag collisions.
265
266``` go
267var opt = godog.Options{
268 Output: colors.Colored(os.Stdout),
269 Format: "progress", // can define default values
270}
271
272func init() {
273 godog.BindFlags("godog.", flag.CommandLine, &opt)
274}
275
276func TestMain(m *testing.M) {
277 flag.Parse()
278 opt.Paths = flag.Args()
279
280 status := godog.RunWithOptions("godogs", func(s *godog.Suite) {
281 FeatureContext(s)
282 }, opt)
283
284 if st := m.Run(); st > status {
285 status = st
286 }
287 os.Exit(status)
288}
289```
290
291Then you may run tests with by specifying flags in order to filter
292features.
293
294```
295go test -v --godog.random --godog.tags=wip
296go test -v --godog.format=pretty --godog.random -race -coverprofile=coverage.txt -covermode=atomic
297```
298
299The following example does not bind godog flags, instead manually
300configuring needed options.
301
302``` go
303func TestMain(m *testing.M) {
304 status := godog.RunWithOptions("godog", func(s *godog.Suite) {
305 FeatureContext(s)
306 }, godog.Options{
307 Format: "progress",
308 Paths: []string{"features"},
309 Randomize: time.Now().UTC().UnixNano(), // randomize scenario execution order
310 })
311
312 if st := m.Run(); st > status {
313 status = st
314 }
315 os.Exit(status)
316}
317```
318
319You can even go one step further and reuse **go test** flags, like
320**verbose** mode in order to switch godog **format**. See the following
321example:
322
323``` go
324func TestMain(m *testing.M) {
325 format := "progress"
326 for _, arg := range os.Args[1:] {
327 if arg == "-test.v=true" { // go test transforms -v option
328 format = "pretty"
329 break
330 }
331 }
332 status := godog.RunWithOptions("godog", func(s *godog.Suite) {
333 godog.SuiteContext(s)
334 }, godog.Options{
335 Format: format,
336 Paths: []string{"features"},
337 })
338
339 if st := m.Run(); st > status {
340 status = st
341 }
342 os.Exit(status)
343}
344```
345
346Now when running `go test -v` it will use **pretty** format.
347
348### Tags
349
350If you want to filter scenarios by tags, you can use the
351`-t=<expression>` or `--tags=<expression>` where `<expression>`
352is one of the following:
353
354- `@wip` - run all scenarios with wip tag
355- `~@wip` - exclude all scenarios with wip tag
356- `@wip && ~@new` - run wip scenarios, but exclude new
357- `@wip,@undone` - run wip or undone scenarios
358
359### Configure common options for godog CLI
360
361There are no global options or configuration files. Alias your common or
362project based commands: `alias godog-wip="godog --format=progress
363--tags=@wip"`
364
365### Testing browser interactions
366
367**godog** does not come with builtin packages to connect to the browser.
368You may want to look at [selenium](http://www.seleniumhq.org/) and
369probably [phantomjs](http://phantomjs.org/). See also the following
370components:
371
3721. [browsersteps](https://github.com/llonchj/browsersteps) - provides
373 basic context steps to start selenium and navigate browser content.
3742. You may wish to have [goquery](https://github.com/PuerkitoBio/goquery)
375 in order to work with HTML responses like with JQuery.
376
377### Concurrency
378
379In order to support concurrency well, you should reset the state and
380isolate each scenario. They should not share any state. It is suggested to
381run the suite concurrently in order to make sure there is no state
382corruption or race conditions in the application.
383
384It is also useful to randomize the order of scenario execution, which you
385can now do with **--random** command option.
386
387**NOTE:** if suite runs with concurrency option, it concurrently runs
388every feature, not scenario per different features. This gives
389a flexibility to isolate state per feature. For example using
390**BeforeFeature** hook, it is possible to spin up costly service and shut
391it down only in **AfterFeature** hook and share the service between all
392scenarios in that feature. It is not advisable though, because you are
393risking having a state dependency.
394
395## Contributions
396
397Feel free to open a pull request. Note, if you wish to contribute an extension to public (exported methods or types) -
398please open an issue before to discuss whether these changes can be accepted. All backward incompatible changes are
399and will be treated cautiously.
400
401Reach out to the community on our [Cucumber Slack Community](https://cucumberbdd.slack.com/).
402Join [here](https://cucumberbdd-slack-invite.herokuapp.com/).
403
404### Popular Cucumber Slack channels for Godog:
405- [#help-godog](https://cucumberbdd.slack.com/archives/CTNL1JCVA) - General Godog Adoption Help
406- [#committers-go](https://cucumberbdd.slack.com/archives/CA5NJPDJ4) - Golang focused Cucumber Contributors
407- [#committers](https://cucumberbdd.slack.com/archives/C62D0FK0E) - General Cucumber Contributors
408
409## License
410- **Godog** is licensed under the [MIT][license]
411- **Gherkin** is licensed under the [MIT][license] and developed as
412a part of the [cucumber project][cucumber]
413
414[godoc]: http://godoc.org/github.com/cucumber/godog "Documentation on godoc"
415[golang]: https://golang.org/ "GO programming language"
416[behat]: http://docs.behat.org/ "Behavior driven development framework for PHP"
417[cucumber]: https://cucumber.io/ "Behavior driven development framework"
418[gherkin]: https://github.com/cucumber/gherkin-go "Gherkin3 parser for GO"
419[license]: https://en.wikipedia.org/wiki/MIT_License "The MIT license"
420