如何在Phoenix测试中创建会话?

时间:2016-07-01 04:01:50

标签: elixir phoenix-framework

我们尝试了各种方法,所有这些方法都产生了不同类型的错误,幸运的是我现在还记不起来了。我们能够使用bypass_through和朋友,直到最近我们需要真实的会话。

这是基于Plug测试我能够整理的内容:

def conn_with_session do
        build_conn
        |> get("/")
        |> recycle
        |> Plug.Session.call(Plug.Session.init(store: Plug.ProcessStore, key: "_app_key"))
        |> fetch_session
      end

其中Plug.ProcessStore从此处https://github.com/elixir-lang/plug/blob/master/test/test_helper.exs#L6

复制粘贴

有更方便/直接的方法吗?

1 个答案:

答案 0 :(得分:-1)

我尝试让集成测试模仿您的API的真正消费者。真正的API消费者无法访问原始会话,因此您的测试也不应该。

如果您的端点用于使用API​​密钥设置会话,则此类操作可能有效:

defmodule MyIntegrationTest do
  setup %{conn: conn} do
    {:ok, conn: sign_in(conn, "TEST_API_KEY")}
  end

  test "Session is authenticated", %{conn: conn} do
    conn = get(conn, some_protected_path(conn))
    assert conn.status == 200 
  end    

  def sign_in(conn, api_key) do
    # You can make changes to conn.session in the controller action for
    # sign_in_path and those changes will be reflected on the conn returned here.

    post(conn, sign_in_path(conn, :create), %{api_key: api_key}})
  end
end