【发布时间】: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方法是一个好方法吗?任何解决方案或指导将不胜感激!
【问题讨论】:
-
@anothermh 看到了那个帖子,但那是 6 年前的事了,不确定它是否仍然是 rails 5 中的相同约定
标签: ruby api controller ruby-on-rails-5 http-status-codes