我为测试用例编写了一个小宏。
defmodule ControllerTest do
@required [:phone, :country]
defmacro create(fields) do
quote do
without = length(unquote(@required) -- unquote(field)
if without != 0 do
Enum.map(unquote(@required), fn(field) ->
member = Enum.member?(unquote(fields), field)
if member == false do
expected_error = String.to_atom(Atom.to_string(field) <> " " <> "can't be blank")
expected = {:error, expected_error}
assert expected == {:error, expected_error}
end
end)
else
expect = {:success, "Record created"}
assert expect == {:success, "Record created"}
end
end
end
end
没有断言它的工作正常。但是当我尝试使用assert时,它说assert是未定义的。我在模块中尝试了import ExUnit.Assertions
,但仍未确定相同的assert
。
在宏内部使用assert的可行解决方案是什么?
由于
答案 0 :(得分:0)
在使用import
之前,您需要在quote
内添加assert
。在quote
之前添加它不会在assert
内提供quote
。
defmacro create(fields) do
quote do
import ExUnit.Assertions
without = ...
...
end
end
此外,您的Enum.map
可以简化为:
for field <- unquote(@required), field not in unquote(fields) do
expected_error = String.to_atom(Atom.to_string(field) <> " " <> "can't be blank")
expected = {:error, expected_error}
assert expected == {:error, expected_error}
end