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

问题描述 投票:0回答:1

目前使用常见的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方法,但仍然没有运气。

testing phoenix-framework plug
1个回答
0
投票

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

对于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
© www.soinside.com 2019 - 2024. All rights reserved.