5
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Ginkgoを使ってみる

Last updated at Posted at 2015-01-09

ginkgo使ってみる

ginkgoのインストール

install
$ go get github.com/onsi/ginkgo/ginkgo
$ go get github.com/onsi/gomega

packageディレクトリ準備

packageディレクトリ作成
$ mkdir $GOPATH/src/fuga
$ cd $GOPATH/src/fuga
初期化
$ ginkgo bootstrap

↑これでfuga_suite_test.go が生成される。

fuga_suite_test.go
package fuga_test

import (
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"

	"testing"
)

func TestFuga(t *testing.T) {
	RegisterFailHandler(Fail)
	RunSpecs(t, "Fuga Suite")
}

テストコード実装

雛形生成

fugaのテストコード雛形生成
$ ginkgo generate fuga

↑これで fuga_test.go が生成される

fuga_test.go
package fuga_test

import (
	. "fuga"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

var _ = Describe("Fuga", func() {

})

"dot import" は、このパッケージ名前空間に関数やクラスをimportする。

テストコード実装

fuga_test.go に サンプルのコードそのまま写した

fuga_test.go写経版
package fuga_test

import (
	. "fuga"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

var _ = Describe("Fuga", func() {
	var (
		longBook  Book
		shortBook Book
	)

	BeforeEach(func() {
		longBook = Book{
			Title:  "les Miserables",
			Author: "Victor Hugo",
			Pages:  1488,
		}

		shortBook = Book{
			Title:  "Fox In Socks",
			Author: "Dr. Seuss",
			Pages:  24,
		}
	})

	Describe("Categorizing book length", func() {
		Context("With more than 300 pages", func() {
			It("should be a novel", func() {
				Expect(longBook.CategoryByLength()).To(Equal("NOVEL"))
			})
		})
		Context("With fewer than 300 pages", func() {
			It("sould be a short story", func() {
				Expect(shortBook.CategoryByLength()).To(Equal("SHORT STORY"))
			})
		})
	})
})

ライブラリ実装する

fuga.go
package fuga

type Book struct {
	Title  string
	Author string
	Pages  int
}

func (b *Book) CategoryByLength() (category string) {
	if b.Pages < 300 {
		return "SHORT STORY"
	}
	if 300 < b.Pages {
		return "NOVEL"
	}
	return "OTHER"
}

テスト実行

テスト実行
$ ginkgo
実行結果
Running Suite: Fuga Suite
=========================
Random Seed: 1419579406
Will run 2 of 2 specs

••
Ran 2 of 2 Specs in 0.004 seconds
SUCCESS! -- 2 Passed | 0 Failed | 0 Pending | 0 Skipped PASS

Ginkgo ran 1 suite in 1.395949245s
Test Suite Passed

テスト通った!!

ファイル監視

ファイル監視
$ ginkgo watch

↑これで監視プロセスが起動。ファイルの更新時にテストを実行してくれる。

5
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?