gpt4 book ai didi

ruby-on-rails - 使用rspec验证模型时测试错误消息

转载 作者:行者123 更新时间:2023-12-03 08:54:09 28 4
gpt4 key购买 nike

我已经继承了Rails api,并且正在尝试测试 Controller 。我有一个端点“/api/v1/vitcords”,在其中创建新的vitcords。视频模型只有一个验证名称。因此,我的疑问是如何测试当我创建一个没有指定名称的新视频时,出现我想要的消息错误,在这种情况下为“必须指定Vitcord名称”。谢谢。

这是Vcord模型

class Vcord
include Mongoid::Document
include Mongoid::Timestamps
include Mongoid::Spacial::Document
include Concerns::Vitcord::M3u8
include Concerns::Vitcord::User

# Validations
validates_presence_of :name

# Atributes
field :name, type: String
field :location, type: Array, spacial: true
field :address, type: String
field :closed, type: Boolean, default: false
field :public, type: Boolean, default: false
field :thumb, type: String

end

这是 Controller video_controller.rb
module Api::V1
class VitcordsController < ApiController
def create
user = current_resource_owner

# Validation
param! :name, String, required: true
param! :location, Hash, required: false
param! :address, String, required: false

ap params[:location]
ap params[:location][:latitude]
ap params[:location][:longitude]

# Creating
vcord = Vcord.new()
vcord.name = params[:name] if params[:name]
if params[:location] && params[:location]['latitude'] && params[:location]['longitude']
vcord.location = {
lng: params[:location]['longitude'],
lat: params[:location]['latitude']
}
end
vcord.address = params[:address] if params[:address]
vcord.creator = user
if vcord.save
vcord.members.each do |member|
Notification.generate_notification_for_vitcord_invited(vcord, member)
end
@vitcord = vcord
else
error(:internal_server_error, ["Vitcord name has to be specified"], nil)
end
end
end

这是规格
require 'rails_helper'

describe "POST /api/v1/vitcords" do
before(:each) do
db_drop

post "/oauth/token", {
:grant_type => 'assertion',
:assertion => TOKEN
}

@token = response_json['access_token']
end

it "sends an error if a vitcord is created with name nil" do
header 'Authorization', "Bearer #{@token}"
post '/api/v1/vitcords', {
address: "Calle Rue del Percebe",
location: {
latitude: 40.7127837,
longitude: -74.00594130000002
}
}

//This does not work but it would be something like this
expect(error).to eq("Name has to be specified")
end
end

最佳答案

好吧,您应该重构代码,但是回答您的问题,您可以通过执行以下操作向对象添加错误(看起来我使用的是@vcord而不是vcord):

@vcord.errors.add(:name, 'Vitcord name has to be specified')

(如您在这里看到的 http://api.rubyonrails.org/classes/ActiveModel/Errors.html#method-i-add)
并在您的测试中:
expect(assigns(:vcord).errors.name).to eq('Vitcord name has to be specified').

关于ruby-on-rails - 使用rspec验证模型时测试错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31729423/

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