将HTTP状态代码201设置为动作控制器导轨中的API响应

时间:2019-06-13 08:31:47

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

我是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方法是一个好方法吗?任何解决方案或指导将不胜感激!

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

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