我为测试用例编写了一个小宏。
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。
在宏中使用断言可能的解决方案是什么?
谢谢
发布于 2018-02-20 07:28:07
在使用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}
endhttps://stackoverflow.com/questions/48878761
复制相似问题