gpt4 book ai didi

ruby-on-rails - 如何 stub after_create 回调保存!在模型中?

转载 作者:数据小太阳 更新时间:2023-10-29 07:38:14 25 4
gpt4 key购买 nike

我收到以下错误:

输出:

1) LabelsController#create label is new creates a new label
Failure/Error: post :create, attributes[:label], format: :json
NoMethodError:
undefined method `save!' for nil:NilClass
# ./app/models/labeling.rb:17:in `update_target'

在标签模型中:

after_create :update_target

def update_target
self.target.save!
end

测试:

require 'spec_helper'
describe LabelsController do
before(:each) do
controller.stub(:current_user).and_return(mock_model(User))
stub_request(:any, "www.example.com").to_return(status: 200)
end
describe "#create" do
context "label is new" do
it "creates a new label" do
attributes = {
label: {
name: "test",
labeling: {
target_type: "Link", target_id: 1
}
}
}
response.status.should == 200
post :create, attributes[:label], format: :json
end
end
end
end

标签 Controller :

  def create
label = Label.find_by_name(params[:name])

labeling = label.labelings.build do |lb|
lb.user_id = current_user.id
lb.target_type = params[:labeling][:target_type]
lb.target_id = params[:labeling][:target_id]
end

if labeling.save
render json: {
name: label.name,
id: label.id,
labeling: {
id: labeling.id
}
}
end
end

最佳答案

从外观上看,数据库中没有 ID 为 1 的目标,因此在您引用 self.target 的地方,返回值为 nil。在您的情况下,我要做的是首先创建一个目标,然后将其 id 传递给属性散列:

target = Traget.create!
attributes = {
label: {
name: "test",
labeling: {
target_type: "Link", target_id: target.id
}
}
}

这样你就不需要 stub 了。如果你真的必须 stub 你可以使用 RSpecs any_instance 方法的方法:

Labeling.any_instance.stub(:update_target).and_return(true)

关于ruby-on-rails - 如何 stub after_create 回调保存!在模型中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13160324/

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