我正在编写一个我想测试的项目,既可以使用 ExUnit 自动测试,也可以与 iex 交互。假设我的项目如下所示:
[mto@bgobuildwin8g sample]$ tree
.
├── config
│ └── config.exs
├── fixtures
│ └── complex_struct.exs
├── lib
│ └── the_function.ex
├── mix.exs
├── README.md
└── test
└── the_test.exs
4 directories, 7 files
[mto@bgobuildwin8g sample]$ cat lib/the_function.ex
defmodule TheFunction do
def the_function ({a, b, c}) do
a / b + c
end
end
[mto@bgobuildwin8g sample]$ cat fixtures/complex_struct.exs
defmodule ComplexStruct do
def complex_struct do
{2, 1, 1}
end
end
[mto@bgobuildwin8g sample]$ cat test/the_test.exs
defmodule IexandtestTest do
Code.load_file("fixtures/complex_struct.exs")
use ExUnit.Case
doctest Iexandtest
test "the test" do
assert (TheFunction.the_function (ComplexStruct.complex_struct())) == 3
end
end
我现在可以运行混合测试,它会找到fixtures/complex_struct.exs 以便测试成功执行。我也喜欢使用以下命令调试我的代码
iex -S mix
这样我就可以访问 lib/the_function.ex 并对其进行调试。
iex(1)> TheFunction.the_function({1,2,3})
3.5
但是我无法访问fixtures/complex_struct.exs,除非我像这样加载它:
iex(1)> TheFunction.the_function(ComplexStruct.complex_struct())
** (UndefinedFunctionError) undefined function ComplexStruct.complex_struct/0 (module ComplexStruct is not available)
ComplexStruct.complex_struct()
iex(1)> Code.load_file("fixtures/complex_struct.exs")
[{ComplexStruct,
<<70, 79, 82, 49, 0, 0, 5, 28, 66, 69, 65, 77, 69, 120, 68, 99, 0, 0, 0, 137, 131, 104, 2, 100, 0, 14, 101, 108, 105, 120, 105, 114, 95, 100, 111, 99, 115, 95, 118, 49, 108, 0, 0, 0, 4, 104, 2, 100, 0, ...>>}]
iex(2)> TheFunction.the_function(ComplexStruct.complex_struct())
3.0
什么决定了 iex 加载的内容,以及当我运行 iex -S mix 时,如何使 lib 中的所有模块和所有固定装置可用?