【问题标题】:Set http status code 201 to an API response in action controller rails将 http 状态代码 201 设置为动作控制器 rails 中的 API 响应
【发布时间】:2019-06-13 08:31:47
【问题描述】:

我是 Rails 新手,我正在构建一个用作 API 的 Rails 应用程序。目前我没有任何模型或数据库,只有一个 Api::ProductController 控制器:

class Api::ProductController < ApplicationController

  def create
    Rails.logger.info "product was created and the parameters are #{product_params[:name]}, #{product_params[:age]}"
  end

  private

  def product_params
    params.permit(:name, :age)
  end
end

。当我继续写请求 Rspec 时:


RSpec.describe Api::productsController, type: :request do

  it "creates a product" do
    post "/api/products", params: { name: "name", age: "22"}

    expect(response).to have_http_status(:created)
    expect(response.body).to include("product was successfully created.")
  end
end

但是当我在命令行上运行请求 rspec 测试时,我收到以下错误:

Failure/Error: expect(response).to have_http_status(:created)
       expected the response to have status code :created (201) but it was :no_content (204)

我的问题是如何将状态码设置为 :created (201)? Head方法是一个好方法吗?任何解决方案或指导将不胜感激!

【问题讨论】:

标签: ruby api controller ruby-on-rails-5 http-status-codes


【解决方案1】:

返回创建项目的 json 表示是很常见的。 现在您的操作没有返回数据。

尝试使用render json: product_params.to_json, status: :created

【讨论】:

  • 将这段代码添加到创建操作中?在 Rails.logger 下?
【解决方案2】:
  def create
    Rails.logger.info "product was created and the parameters are #{product_params[:name]}, #{product_params[:age]}"
    render status: :created
  end

【讨论】:

  • 这将通过第一个测试断言,但您的第二个断言仍然会失败,但我没有提供解决方案,因为我认为您对身体的测试是错误的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-14
  • 2021-04-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多