gpt4 book ai didi

ruby-on-rails - 使用 RSpec 测试 Rails API Controller POST

转载 作者:数据小太阳 更新时间:2023-10-29 08:29:59 26 4
gpt4 key购买 nike

正如标题所示,我只是想用 RSpec 测试我的 API Controller 中的创建操作。 Controller 看起来像:

module Api
module V1
class BathroomController < ApplicationController
skip_before_action :verify_authenticity_token, only: [:create]`

def create
bathroom = Bathroom.new(bathroom_params)
bathroom.user = current_user
if bathroom.save
render json: { status: 'SUCCESS', message: 'Saved new bathroom', bathrooms: bathroom }, status: :ok
end
end

private
def bathroom_params
params.require(:bathroom).permit(:establishment, :address, :city, :state, :zip, :gender, :key_needed, :toilet_quantity)
end

end
end
end

现在,它正在做它应该做的事情,这很棒。然而,测试......不是那么多。这是我的测试部分:

describe "POST #create" do
let!(:bath) {{
establishment: "Fake Place",
address: "123 Main St",
city: "Cityton",
state: "NY",
zip: "11111",
gender: "Unisex",
key_needed: false,
toilet_quantity: 1
}}
let!(:params) { {bathroom: bath} }
it "receives bathroom data and creates a new bathroom" do
post :create, params: params

bathroom = Bathroom.last
expect(bathroom.establishment).to eq "Fake Place"
end
end

我敢肯定这里有不止一件事是错的,但我很难找到有关正确测试方法的大量信息。任何见解或建议将不胜感激。

最佳答案

我会完全跳过 Controller 规范。 Rails 5 几乎将 ActionController::TestCase(RSpec 包装为 Controller 规范)委托(delegate)给垃圾抽屉。 Controller 测试不会发送真正的 http 请求,也不会排除 Rails 的关键部分,如路由器和中间件。很快就会完全贬值并委托(delegate)给一个单独的 gem。

相反,您想使用请求规范。

RSpec.describe "API V1 Bathrooms", type: 'request' do
describe "POST /api/v1/bathrooms" do
context "with valid parameters" do
let(:valid_params) do
{
bathroom: {
establishment: "Fake Place",
address: "123 Main St",
city: "Cityton",
state: "NY",
zip: "11111",
gender: "Unisex",
key_needed: false,
toilet_quantity: 1
}
}
end

it "creates a new bathroom" do
expect { post "/api/v1/bathrooms", params: valid_params }.to change(Bathroom, :count).by(+1)
expect(response).to have_http_status :created
expect(response.headers['Location']).to eq api_v1_bathroom_url(Bathroom.last)
end

it "creates a bathroom with the correct attributes" do
post "/api/v1/bathrooms", params: valid_params
expect(Bathroom.last).to have_attributes valid_params[:bathroom]
end
end

context "with invalid parameters" do
# testing for validation failures is just as important!
# ...
end
end
end

同时发送一堆垃圾,例如 render json: { status: 'SUCCESS', message: 'Saved new bathroom', bathrooms: bathroom }, status: :ok 是一种反模式。

作为响应,您应该只发送一个 201 CREATED 响应,其中的位置 header 包含新创建资源的 URL 或包含新创建资源的响应正文。

def create
bathroom = current_user.bathrooms.new(bathroom_params)
if bathroom.save
head :created, location: api_v1_bathroom_url(bathroom)
else
head :unprocessable_entity
end
end

如果您的客户无法通过查看响应代码来判断响应是否成功,那么您就错了。

关于ruby-on-rails - 使用 RSpec 测试 Rails API Controller POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46841281/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com