在宏内部使用ExUnit.Assertions

时间:2018-02-20 05:57:34

标签: elixir ex-unit

我为测试用例编写了一个小宏。

    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的可行解决方案是什么?

由于

1 个答案:

答案 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