ExUnit-如何通过命名的设置函数将上下文传递给描述块中的测试宏

时间:2018-09-05 11:05:35

标签: elixir mix ex-unit

查看ExUnit文档,您可以使用以下模式将属性添加到context结构中:

defmodule KVTest do
  use ExUnit.Case

  setup do
    {:ok, pid} = KV.start_link
    {:ok, pid: pid}
    # "[pid: pid]" also appears to work...
  end

  test "stores key-value pairs", context do
    assert KV.put(context[:pid], :hello, :world) == :ok
    assert KV.get(context[:pid], :hello) == :world

    # "context.pid" also appears to work...
  end
end

但是,在使用describe宏块时,建议您使用以下形式为测试提供设置功能:

defmodule UserManagementTest do
  use ExUnit.Case, async: true

  describe "when user is logged in and is an admin" do
    setup [:log_user_in, :set_type_to_admin]

    test ...
  end

  describe "when user is logged in and is a manager" do
    setup [:log_user_in, :set_type_to_manager]

    test ...
  end

  defp log_user_in(context) do
    # ...
  end
end

哪种方法效果很好,但是没有提到在使用describe宏和命名设置时如何向上下文结构中添加新属性以供在测试中使用。

到目前为止,我已经尝试过(快速总结):

  ...
  describe "when user is logged in and is a manager" do
    setup [:test]

    test(context) do
       IO.puts("#{ inspect context }") # Comes up as 'nil'
    end
  end

  defp test(context) do
    [test: "HALLO"]
  end
  ...

以这种方式创建用于描述块的设置功能时,实际上是否可以操纵测试套件上下文?

1 个答案:

答案 0 :(得分:2)

您正确地进行了设置。命名的设置函数将上下文作为参数,并且它们的返回值自动合并到上下文中。因此,实际上您已经有了:test键可用于测试。

您只需要在测试中将上下文作为 second 参数,就像这样:

describe "when user is logged in and is a manager" do
  setup [:test]

  test "does the right thing", context do
     IO.inspect(context) # Will not come up as nil
  end
end

但是,更有趣的是,您可以使用模式匹配从上下文中获取所需的确切键:

describe "when user is logged in and is a manager" do
  setup [:test]

  test "does the right thing", %{test: test} do
     IO.inspect(test) # "HALLO"
  end
end