2017-03-18 8 views
0

を呼び出す:私はそれのためにテストを書いた**(例外ArgumentError)フラッシュフェッチではない、このようになります私はプラグを持っている私のフェニックスアプリでfetch_flash/2

defmodule MyApp.Web.Plugs.RequireAuth do 
    import Plug.Conn 
    import Phoenix.Controller 
    import MyApp.Web.Router.Helpers 

    def init(_options) do 
    end 

    def call(conn, _options) do 
    if conn.assigns[:user] do 
     conn 
    else 
     conn 
     |> put_flash(:error, "You must be logged in") 
     |> redirect(to: project_path(conn, :index)) 
     |> halt() 
    end 
    end 
end 

defmodule MyApp.Web.Plugs.RequireAuthTest do 
    use MyApp.Web.ConnCase 

    import MyApp.Web.Router.Helpers 

    alias MyApp.Web.Plugs.RequireAuth 
    alias MyApp.Accounts.User 

    setup do 
    conn = build_conn() 

    {:ok, conn: conn} 
    end 

    test "user is redirected when current user is not set", %{conn: conn} do 
    conn = RequireAuth.call(conn, %{}) 

    assert redirected_to(conn) == project_path(conn, :index) 
    end 

    test "user is not redirected when current user is preset", %{conn: conn} do 
    conn = conn 
    |> assign(:user, %User{}) 
    |> RequireAuth.call(%{}) 

    assert conn.status != 302 
    end 
end 

Iそれは私に次のエラーが返され、私のスペックを実行します。

1) test user is redirected when current user is not set (MyApp.Web.Plugs.RequireAuthTest) 
    test/lib/web/plugs/require_auth_test.exs:15 
    ** (ArgumentError) flash not fetched, call fetch_flash/2 
    stacktrace: 
     (phoenix) lib/phoenix/controller.ex:1231: Phoenix.Controller.get_flash/1 
     (phoenix) lib/phoenix/controller.ex:1213: Phoenix.Controller.put_flash/3 
     (my_app) lib/my_app/web/plugs/require_auth.ex:14: MyApp.Web.Plugs.RequireAuth.call/2 
     test/lib/web/plugs/require_auth_test.exs:16: (test) 

私は私のプラグから、この行削除:

を10
put_flash(:error, "You must be logged in") 

仕様は問題なく通過します。私は間違っているの?

答えて

2

あなたの例はProgramming Phoenixに記載されています。その解決策は、Phoenix.ConnTestのbypass_through/3でルータレイヤーをバイパスすることです。

使用テストスイートでは、このような何か:

setup %{conn: conn} do 
    conn = 
    conn 
    |> bypass_through(Rumbl.Router, :browser) 
    |> get("/") 
    {:ok, %{conn: conn}} 
end 

それはあなたの有効なフラッシュおよびセッションのサポートを提供します。

関連する問題