0

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

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

谢谢

4

1 回答 1

0

使用前需要在import里面加上。之前添加它不会使内部可用。quoteassertquoteassertquote

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
于 2018-02-20T07:28:07.947 回答