【问题标题】:How to test controller methods that use HEAD in Phoenix如何在 Phoenix 中测试使用 HEAD 的控制器方法
【发布时间】:2018-06-07 22:14:00
【问题描述】:

目前文档清晰且充满活力,包含常见的 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)

但我收到一条错误消息,提示未收到回复,而我在 conn.resp_headers 中添加了 resp_header 中没有的内容

我错过了什么吗?我还尝试使用Plug.ConnTest 的方法build_connHEAD 方法传递给它,但仍然没有运气。

【问题讨论】:

    标签: testing phoenix-framework plug


    【解决方案1】:

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

    对于HEAD 路由:

    • 路由器中的动词必须是get,例如:get '/items', :index
    • 如果要共享路径,只需在控制器方法中返回的连接上添加put_resp_header,响应中只会发送标头
    • 响应码不是204也没关系,按照w3c doc'sHEAD请求可以有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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-20
      • 2019-07-08
      • 1970-01-01
      • 2023-01-30
      • 1970-01-01
      • 1970-01-01
      • 2016-01-05
      • 1970-01-01
      相关资源
      最近更新 更多