Technofara

Golangエンジニア!仕事で必要になって勉強した事とか、新しい事とか色々まとめたりを緩くやります。技術系と思考系だけにしておきます、

# BDDの勉強にと、何故かPlayframwork2でscalaとspecs2を使ってみた。

BDDってなんなの?

よく聞くTDDは、プログラムの動作が正しいか検証する為の「テスト」 BDDは、美瑛ビアテスト駆動開発 振る舞いを検証する為の「テスト」 顧客の言葉で書くテスト はて?とりあえず、理解するためにも体に覚え込ませるとします。

さて

play2(scala)を勉強中という事もあるので play2用specs2というのを使って勉強します。

準備

$ vim build.sbt

libraryDependencies ++= Seq(
  jdbc,
  anorm,
  cache,
  "org.specs2" %% "specs2" % "2.3.4" % "test"
)

org.specs2...という行を追加しました。 これを書いておくと、実行時に必要なライブラリが存在しない場合は、作成してくれます。 便利

書き方

xUnit的

テストケース

import org.specs2.mutable._

class TestSpec extends Specification {
  "The 'Hello world' string" should {    
    "contain 11 characters" in {         
      "Hello world" must have size(11)   
    }                                    
    "start with 'Hello'" in {            
      "Hello world" must startWith("Hello")
    }                                    
    "end with 'world'" in {              
      "Hello world" must endWith("world")
    }                                    
  }                                      
}                                        

テスト実行

$ play test
...
...
...
[info] TestSpec
[info]
[info] The 'Hello world' string should
[info] + contain 11 characters
[info] + start with 'Hello'
[info] + end with 'world'
[info]
[info] Total for specification HelloSpec
[info] Finished in 82 ms
[info] 3 examples, 0 failure, 0 error

specification

テストケース

import org.specs2._                                        

class TestSpec extends Specification { 

  def is = s2"""
  This is a specification to check the 'Hello world' string

  The 'Hello world' string should
  contain 11 characters                   $e1
  start with 'Hello'                      $e2
  end with 'world'                        $e3
  """

  def e1 = "Hello world" must have size(11)
  def e2 = "Hello world" must startWith("Hello")
  def e3 = "Hello world" must endWith("world")
}

テスト実行

$ play test
...
...
[info] TestSpec
[info]   This is a specification to check the 'Hello world' string
[info]
[info]   The 'Hello world' string should
[info]   + contain 11 characters
[info]   + start with 'Hello'
[info]   + end with 'world'
[info]   
[info] Total for specification TestSpec
[info] Finished in 9 ms
[info] 3 examples, 0 failure, 0 error

結果

書き方は違うけど、同じ結果を得ることができた。 この違いがどこまで影響出るのかまだわからないけど、とりあえずなれるまで両方やる。

Specification

http://etorreborre.github.io/specs2/guide/org.specs2.guide.Matchers.html