【问题标题】:How to create session in Phoenix tests?如何在 Phoenix 测试中创建会话?
【发布时间】:2016-11-03 08:39:28
【问题描述】:

我们尝试了多种方法,但都产生了不同类型的错误,幸好我现在不记得了。我们可以使用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

有没有更方便/直接的方法来做到这一点?

【问题讨论】:

  • 我认为这是最短的变种,有already answer。如果使用conn 而不是build_conn,您可能可以省略recycle。这也是assign(conn, :current_user, user) 避免会话检查的好解决方案(您可能知道,但以防万一)

标签: elixir phoenix-framework


【解决方案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

【讨论】:

  • 恐怕API端点不受该问题的影响,因为不涉及cookie机制。我们确实将验收测试作为我们测试套件的一部分。
猜你喜欢
  • 2012-12-28
  • 1970-01-01
  • 1970-01-01
  • 2020-07-05
  • 1970-01-01
  • 2016-06-14
  • 2016-11-15
  • 2010-12-13
  • 2014-06-17
相关资源
最近更新 更多