2
3

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.

Elixir | Doctests #elixir

Posted at

Elixir | Doctests

概要

Doctests によって、 API ドキュメントの内容をテストする

使用方法

@doc に iex の実行コード+結果フォーマットを記述します。

defmodule Doctests do
  @doc ~S"""
  FizzBuzz.

  ## Examples

      iex> Doctests.fizzbuzz(1, 15)
      [1, 2, "Fizz", 4, "Buzz", "Fizz", 7, 8, "Fizz", "Buzz", 11, "Fizz", 13, 14, "FizzBuzz"]
  """
  def fizzbuzz(from, to) when is_integer(from) and is_integer(to) do
    from..to |> Enum.map(&(fizzbuzz/1))
  end
  def fizzbuzz(_from, _to) do
    raise "invalid argument"
  end
  defp fizzbuzz(n) when rem(n, 15) == 0 , do: "FizzBuzz"
  defp fizzbuzz(n) when rem(n, 3) == 0, do: "Fizz"
  defp fizzbuzz(n) when rem(n, 5) == 0, do: "Buzz"
  defp fizzbuzz(n), do: n
end

そして、テストクラスには以下のように記述します

defmodule YourModuleTest do
  use ExUnit.Case, async: true
  doctest YourModule
end

すると、テスト実行時に api コメントの Example が実行されます

$ mix test --trace
YourModuleTest
  * doc at YourModule.fizzbuzz/2 (2) (4.7ms)

iex -S mix の利用して、 Example をコピペ

# プロジェクトの作成
$ mix new doctests

# 手動で実装クラス、テストを作成

# プロジェクトのコンテキストで iex を実行
$ iex -S mix
iex(1)> Doctests.fizzbuzz(1,15)
[1, 2, "Fizz", 4, "Buzz", "Fizz", 7, 8, "Fizz", "Buzz", 11, "Fizz", 13, 14,
 "FizzBuzz"]

# iex の出力結果をそのまま @doc の Examples に貼りつければ doctests 完成

参照

DocTest

2
3
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
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?