LoginSignup
22
16

More than 3 years have passed since last update.

忙しい研究者のためのテストコードとドキュメントの書き方、Elixir編

Last updated at Posted at 2021-01-02

@hmkz さんの「忙しい研究者のためのテストコードとドキュメントの書き方」が素晴らしかったので、Elixirでのやり方をまとめておきます。

Step 0: 環境構築

テスト環境:doctest

Elixir標準のdoctestマクロを使います。(後述するため、ここでは何もしません。

ドキュメント生成ライブラリ:ExDoc

Using ExDoc with Mix」に従って、depsにex_docを追加し、 "mix deps.get" するだけです。

サンプルプロジェクト

使い方を見ていくためにサンプルプロジェクトを作っておきます。

$ mix new sample
# 中略
$ cd sample
$ vim mix.exs # ex_docをdepsに追加して
$ mix deps.get

Step 1: 関数を書く

算術関数を集めたMathモジュールを作ってみましょう。

モジュールを作り、

$ mkdir lib/sample
$ vim lib/sample/math.ex

欲しい関数のガワだけを作っておきます。

defmodule Sample.Math do
  def add(x, y) do
    :not_implemented
  end
end

Step 2: ドキュメントを書く

関数のドキュメントを書きます。
そして、その使用例を iex> で始まる行に、その結果を次の行に書きます。(これが後にテストされるようになります。

@doc """
# 足し算
addは引数を2つ取り、足し算した結果を返します。

      iex> Sample.Math.add(1,2)
      3
"""
defmodule Sample.Math do
  def add(x, y) do
    :not_implemented
  end
end

Step 3: テストする

対象モジュールをテスト対象に含めるために test/sample_test.ex に一行追加すれば、

defmodule SampleTest do
  use ExUnit.Case
  doctest Sample
  doctest Sample.Math # 追加行、doctestマクロの後に対象モジュール名を書く

  # 略
end

テストできるようになります。

$ mix test
Compiling 1 file (.ex)
warning: variable "x" is unused (if the variable is not meant to be used, prefix it with an underscore)
  lib/sample/math.ex:9: Sample.Math.add/2

warning: variable "y" is unused (if the variable is not meant to be used, prefix it with an underscore)
  lib/sample/math.ex:9: Sample.Math.add/2

.

  1) doctest Sample.Math.add/2 (1) (SampleTest)
     test/sample_test.exs:4
     Doctest failed
     doctest:
       iex> Sample.Math.add(1,2)
       3
     code:  Sample.Math.add(1, 2) === 3
     left:  :not_implemented
     right: 3
     stacktrace:
       lib/sample/math.ex:6: Sample.Math (module)

.

Finished in 0.04 seconds
2 doctests, 1 test, 1 failure

関数のロジックが未実装なので、ドキュメントの使用例とその結果が一致せずテストが失敗しています。

Step 4: 実装する

テストをパスするように実装します。

defmodule Sample.Math do
  @doc """
  # 足し算
  addは引数を2つ取り、足し算した結果を返します。

      iex> Sample.Math.add(1,2)
      3
  """
  def add(x, y) do
    x + y
  end
end

実装できたら、再度テストしましょう。

$ mix test
Compiling 1 file (.ex)
...

Finished in 0.04 seconds
2 doctests, 1 test, 0 failures

テストがパスするようになりました♪

Step 5: ドキュメントを生成する

ドキュメントの生成は "mix docs" でできます。

$ mix docs
# 中略
Generating docs...
View "html" docs at "doc/index.html"
View "epub" docs at "doc/sample.epub" # epubも出力できるんですね!

index.htmlをブラウザで開いて該当モジュールを見ると、、

image.png

キレイなドキュメントが出力されています。いぇい!

参考

doctestの書き方は以下が参考になります。

Elixirのドキュメントの書き方は以下が参考になります。

以上です。

Happy Hacking with Elixir!!

22
16
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
22
16