如何测试在Phoenix中使用HEAD的控制器方法

时间:2018-06-07 02:46:00

标签: testing phoenix-framework plug

目前,使用常见的HTTP动词,文档清晰明了,但我们今天开始实施一些HEAD路由,并且测试的方式与其他路由不同。

测试一个GET方法:

conn = get conn, controller_path(conn, :controller_method, params)

所以我认为您只需将get更改为head,但事实并非如此。

这是我的路线:

template_journeys_count_path HEAD /v1/templates/:template_id/journeys GondorWeb.V1.JourneyController :count

和我的控制器方法:

def count(conn, %{"template_id" => template_id}) do count = Templates.get_journey_count(template_id) conn |> put_resp_header("x-total-count", count) |> send_resp(204, "") end

和我的测试:

conn = head conn, template_journeys_count_path(conn, :count, template.id) assert response(conn, 204)

但是我收到一条错误消息,指出没有收到回复,resp_header我添加的内容不在conn.resp_headers

我错过了什么吗?我还尝试使用Plug.ConnTest的方法build_conn设置连接构建,将HEAD方法传递给它,但仍然没有运气。

1 个答案:

答案 0 :(得分:0)

使用邮递员进行更多阅读和测试后确定。 Phoenix会自动将HEAD个请求更改为GET个请求,当凤凰在路由器中查找我的路由时,它正在点击与get路径匹配的路由是:index 1}}方法。

对于HEAD路线:

  • 路由器中的动词必须是get,例如:get '/items', :index
  • 如果您想共享路径,只需在控制器方法中添加返回的连接上的put_resp_header,只会在响应中发送标题
  • 响应代码不是204,根据w3c doc's HEAD请求可以有200响应
  • 测试HEAD请求,您只需将get更改为head并测试response_headers,并且未发送任何正文。

显示我的更改......这是我的路由器:

get "/journeys", JourneyController, :index

我的控制器方法:

def index(conn, %{"template_id" => template_id}) do
    journeys = Templates.list_journeys(template_id)
    conn
    |> put_resp_header("x-total-count", "#{Enum.count(journeys)}")
    |> render("index.json", journeys: journeys)
end

和我的测试:

test "gets count", %{conn: conn, template: template} do
  conn = head conn, template_journey_path(conn, :index, template.id)
  assert conn.resp_body == ""
  assert Enum.at(get_resp_header(conn, "x-total-count"), 0) == "1"
end