目前,使用常见的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
方法传递给它,但仍然没有运气。
答案 0 :(得分:0)
使用邮递员进行更多阅读和测试后确定。 Phoenix会自动将HEAD
个请求更改为GET
个请求,当凤凰在路由器中查找我的路由时,它正在点击与get
路径匹配的路由是:index
1}}方法。
对于HEAD
路线:
get
,例如:get '/items', :index
put_resp_header
,只会在响应中发送标题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