2017-02-20 57 views
0

我已經找到類似的答案,此herehere,但它似乎並沒有工作。指定當前用戶進行測試

我在測試時將current_user分配給會話時遇到問題。我的測試中都設置了這樣

setup do 
    %User{ 
    id: 123456, 
    name: "MyName", 
    email: "[email protected]", 
    password_hash: Comeonin.Bcrypt.hashpwsalt("password") 
    } |> Repo.insert 

{:ok, user: Repo.get(User, 123456) } 
end 

和我的測試是

test "renders index.html on /coping-strategy", %{user: user} do 
    conn = conn 
     |> assign(:current_user, user) 
     |> get(coping_strategy_path(conn, :index)) 
    assert html_response(conn, 200) =~ "Coping strategies" 
end 

當我在這裏檢查康涅狄格州,current_user已經正確地分配給user。但是,當我在測試過程中檢查控制器中的conn時,current_user總是nil。我也嘗試使用build_conn,但它仍然是零。

這裏是控制器:

def index(conn, _params) do 
    user_id = conn.assigns.current_user.id 
    coping_strategies = Post 
         |> Post.get_coping_strategies(user_id) 
         |> Repo.all 
    render conn, "index.html", coping_strategies: coping_strategies 
end 

如果我嘗試分配比CURRENT_USER其他的東西,那麼就說明,當我檢查控制器的康涅狄格州。因此,如果我在|> assign(:stuff, "test")中添加了測試,那麼我在0123中指定stuff: "test"。如果我在測試和控制器中將current_user更改爲current_user2,它會工作,因爲current_user2會更新並按照我預期的那樣傳遞。

是否有一個原因,我不能指定當前用戶這樣,爲什麼它總是零?有沒有什麼步驟我特意爲current_user執行此操作?

編輯

這裏就是CURRENT_USER正在在身份驗證插件設置

def call(conn, repo) do 
    user_id = get_session(conn, :user_id) 
    user = user_id && repo.get(Healthlocker.User, user_id) 
    assign(conn, :current_user, user) 
end 
+0

你能發佈在你的應用中分配'current_user'的代碼嗎(認證插件?)?即使已設置,您可能會將其設置爲「無」。 – Dogbert

+0

@Dogbert看起來像它。當我運行測試時,用戶是'nil'。 – Katherine

回答

2

既然你在測試中assigns直接設置:current_user,你需要跳過取出由用戶會話的:user_id如果assigns包含:current_user在auth插件中:

def call(conn, repo) do 
    if conn.assigns[:current_user] do 
    conn 
    else 
    user_id = get_session(conn, :user_id) 
    user = user_id && repo.get(Healthlocker.User, user_id) 
    assign(conn, :current_user, user) 
    end 
end