2017-09-05 192 views
1

我有一個控制器,它看起來像這樣API控制器獲取錯誤:鳳凰:無論PARAMS

defmodule PrefectWeb.DocumentController do 
    use PrefectWeb, :controller 

    alias Prefect.Queue 

    def create(conn, params) do 
    case Prefect.add(Queue, struct(Prefect.Document, params[:id])) do 
     nil -> conn 
     |> put_status(404) 
     |> render("error.json") 
     status -> {:ok, status} 
    end 
    end 
end 

的創建方法應該添加params[:id]Queue過程。我的單元測試是這樣的:

defmodule PrefectWeb.DocumentControllerTest do 
    use ExUnit.Case, async: true 
    use PrefectWeb.ConnCase 

    setup do 
    params = [ 
     env: "test", 
     id: 1, 
    ] 

    [params: params] 
    end 

    test "creation", %{conn: conn, params: params} do 
    conn 
    |> post(document_path(conn, :create, params)) 

    assert json_response(conn, 422) 
    end 
end 

該規範返回此錯誤:

1) test creation (PrefectWeb.DocumentControllerTest) 
    test/prefect_web/controllers/document_controller_test.exs:27 
    ** (Protocol.UndefinedError) protocol Enumerable not implemented for nil. This protocol is implemented for: Date.Range, File.Stream, Function, GenEvent.Stream, HashDict, HashSet, IO.Stream, List, Map, MapSet, Range, Stream 

如果我改變控制器功能給他:

def create(conn, %{"params" => params}) do 
    ... 
end 

我得到這個錯誤:

1) test creation (PrefectWeb.DocumentControllerTest) 
    test/prefect_web/controllers/document_controller_test.exs:27 
    ** (Phoenix.ActionClauseError) could not find a matching PrefectWeb.DocumentController.create clause 
    to process request. This typically happens when there is a 
    parameter mismatch but may also happen when any of the other 
    action arguments do not match. The request parameters are: 

     %{"env" => "test", "id" => "1"} 

爲什麼我不能通過params[:id]正確的創建方法?

更新

添加請求頭並沒有幫助:

|> put_req_header("content-type", "application/json") 

回答

1

該參數映射是字符串,而不是基於原子。試着改變你的控制器

defmodule PrefectWeb.DocumentController do 
    use PrefectWeb, :controller 

    alias Prefect.Queue 

    def create(conn, params) do 
    case Prefect.add(Queue, struct(Prefect.Document, params["id"])) do 
     nil -> conn 
     |> put_status(404) 
     |> render("error.json") 
     status -> {:ok, status} 
    end 
    end 
end 

和測試,以

defmodule PrefectWeb.DocumentControllerTest do 
    use ExUnit.Case, async: true 
    use PrefectWeb.ConnCase 

    setup do 
    params = %{ 
     "env" => "test", 
     "id" => 1 
    } 

    [params: params] 
    end 

    test "creation", %{conn: conn, params: params} do 
    conn 
    |> post(document_path(conn, :create, params)) 

    assert json_response(conn, 422) 
    end 
end 
+1

啊!謝謝。哈,這有點讓人困惑。 –

0

您聲稱在setup創建的康涅狄格州,而不是一個從post返回。嘗試在assert之前重新綁定conn

test "creation", %{conn: conn, params: params} do 
    conn = 
     conn 
     |> post(document_path(conn, :create), params) 

    assert json_response(conn, 422) 
    end 
+0

這使得錯誤'**(Protocol.UndefinedError)協議可枚舉不nil.'實現。 –

+0

注意到另一個問題,回答編輯。 –

+0

啊,很好,但是這帶我們去了我最初所遭受的另一個錯誤。 –