LoginSignup
5
5

More than 5 years have passed since last update.

JasmineでbeforeEachを丁寧に使った方が良い理由

Last updated at Posted at 2012-12-26

次のような簡単なクラスがあるとする。indexというプロパティを持ち、そのプロパティを増やすincrementIndex()とプロパティを減らすdecrementIndex()というメソッドを持つ。なお、クラスはテストから見えるようにexportしている。

root = exports ? this
class root.SomeClass
  constructor: ->
    @index = 0
  incrementIndex: -> @index++
  decrementIndex: -> @index--

beforeEachを意識しないでテストを書くと以下のようになるだろう。ここではまずindexプロパティに3を代入し、それを1増やしたら4になるべきだというテストを書いている。次に逆に1減らすと2になるべきだというテストを書いている。

describe "Object", ->
  object = new SomeClass

  describe ".index", ->
    describe "when index = 3", ->
      object.index = 3

      describe "when next button is clicked", ->
        object.incrementIndex()
        it "returns 4", ->
          expect(object.index).toBe 4

      describe "when previous button is clicked", ->
        object.decrementIndex()
        it "returns 3", ->
          expect(object.index).toBe 2

しかし、このテストは次のように失敗する。

Failing 2 specs

Photos initialized .index when index = 3 when next button is clicked returns 4.
Expected 3 to be 4.

Photos initialized .index when index = 3 when previous button is clicked returns 3.
Expected 3 to be 2.

さらに、ここでテストコードの最後の4行を削除すると、テストは成功する

中で何が起きているのかよくわからないが、上のテストのdescribe同士はお互いに影響を及ぼしあっていることがわかる(わかる方コメントください涙)。

そこでbeforeEachを使って書きなおす。

describe "SomeClass", ->
  object = undefined
  beforeEach ->
    object = new SomeClass

  describe ".index", ->
    describe "when index = 3", ->
      beforeEach ->
        object.index = 3

      describe "when next button is clicked", ->
        beforeEach ->
          object.incrementIndex()
        it "returns 4", ->
          expect(object.index).toBe 4

      describe "when previous button is clicked", ->
        beforeEach ->
          object.decrementIndex()
        it "returns 3", ->
          expect(object.index).toBe 2

すると、テストは無事成功する。丁寧にbeforeEachを使っておいた方が良さそうだとわかる。


ブログやってます:PAPA-tronix !

5
5
2

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
5