How to drown after_create callback save! in the model?

I get the following error:

Output:

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' 

In the marking model:

 after_create :update_target def update_target self.target.save! end 

Test:

 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 

Marking 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 
+4
source share
1 answer

In appearance, you do not have a target with identifier 1 in the database, so when you refer to self.target , the return value is nil. What would I do in your case, first create a target, and then pass your identifier to the attribute hashes:

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

This way you do not need to drown anything. If you really have to stub the method, you can use the RSpecs any_instance method:

 Labeling.any_instance.stub(:update_target).and_return(true) 
+1
source

Source: https://habr.com/ru/post/1443251/


All Articles