在宏中使用 ExUnit.Assertions

Use ExUnit.Assertions inside macro

我写了一个测试用例的小宏

    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

它在没有断言的情况下工作正常。但是当我尝试使用断言时,它说断言未定义。我在模块中尝试了 import ExUnit.Assertions 但仍然是相同的 assert 未定义。

在宏中使用 assert 的可能解决方案是什么?

谢谢

在使用assert之前,您需要在quote中添加import。在 quote 之前添加它不会使 assertquote.

中可用
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