Skip to content

Instantly share code, notes, and snippets.

@r7kamura
Last active June 7, 2017 00:54
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save r7kamura/4381739 to your computer and use it in GitHub Desktop.
Save r7kamura/4381739 to your computer and use it in GitHub Desktop.
Testing memo

Testing

テストにおける依存性などについてのメモです。

Testing Private Methods

Private Methodsのテストを避ける理由

  1. 既にPublic Methodsのテストが存在しているので重複している
  2. Private Methodsは変更される可能性がある(=unstable)
  3. テストによりドキュメント化され利用を推奨してしまう

Private Methodsを多く持つクラスは単一責任原則に違反している可能性が高い。 もしこれらのPrivate Methodsがstableな場合は、 これらのメソッドを新たなオブジェクトとして抽出し、Pubilc Interfaceを定義できる。 抽出されたメソッドは、新たにつくられたオブジェクトの責任を形成する。

Dependency

テスト対象には、内部的に他クラスとの依存性を持つものがある。

class Gear
  attr_reader :wheel

  def initialize(wheel)
    @wheel = wheel
  end

  def gear_inches
    ratio * wheel.width
  end
end

class Wheel
  def width
    rim + (tire * 2)
  end
end

gear = Gear.new(wheel: Wheel.new(1, 2))

このコード例には、幾つかの依存性や前提が存在する。

  • 「widthというメッセージに対応できる」という半ば暗黙的なRoleが存在する
  • Wheelは、そのRoleを持っている
  • Gearは、受け取ったwheelにそのRoleがあると信じている
  • トップレベル(main)では、WheelがそのRoleを持つと信じている
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment