测试应该用tag_id参数中的tag_id更新条目(已经创建)。我知道我可以做到这一点,因为我在postman上试过了,每次都很有效。Rspec告诉我,即使我记录了它的id(这意味着它存在),标签也是无效的。
任何帮助都将不胜感激。
rspec codeerror message with logs
我试着改变输入的方式;我将"www.example.com"放入数组中,希望它将其读取为整数,并且尝试了将数字输入数组的所有其他方法。tag.id" into the array expecting it to read it as an integer and I have tried every other way of inputting the number into the array.
我还知道问题出在数组上,因为一旦我将其留空(又名:[])它工作得非常好。
注意:我100%确定代码有效,因为它适用于 Postman 。
items_controller. rb中用于更新物料的代码:
def update
item = Item.find(params[:id])
item.item_tags.destroy_all
error_exist = false
params[:tag_id].each do |tag_id|
if ItemTag.find_by(tag_id: tag_id) == nil
error_exist = true
break
else
item.tags << Tag.find(tag_id)
end
end
@items = item
if error_exist == false
if current_user.id == item.user_id
if item.update(item_params)
if item.is_sold == true
if item.bids.last != nil
item.bids.last.update_attribute(:is_accepted, true)
end
else
if item.bids.last != nil
item.bids.last.update_attribute(:is_accepted, false)
end
end
render 'items/update'
else
render json: {status: "Error", message: "Item not updated", data:item.errors}, status: :unprocessable_entity
end
else
render json: {status: "Error", message: "Item is not yours"}, status: :unauthorized
end
else
render json: {status: "Error", message: "Invalid tags"}, status: :unprocessable_entity
end
end
private
def item_params
params.permit(:name, :price, :is_auction, :is_sold)
end
注2:不传入任何内容、传入单个tag_id或多个标记都可以。只有当其中一个tag_is不存在时,才会呈现无效标记。
1条答案
按热度按时间4urapxun1#
问题就在这里。
您的测试将
Tag.last.id
作为tag_id
通过,但您的代码按ItemTag.find_by(tag_id: tag_id)
进行搜索。结论是ItemTag
中缺少标记。再深入一点,你不是在问“这个标签存在吗”,而是在问“* 有没有 * 项目已经使用过这个标签”,这看起来很奇怪。
您还将删除相关项目中的所有标记,这将影响不在ItemTag中的标记...
...然后一个接一个地添加新标签。我认为这样做的目的是确保完全替换项目的标签,但这是用
item.tags = tags
完成的。更好的方法是一次性替换标记。