4

我收到以下错误:

输出:

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

标签控制器:

  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

1 回答 1

1

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

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

这样你就不需要存根任何东西。如果你真的必须存根方法,你可以使用 RSpecs any_instance 方法:

Labeling.any_instance.stub(:update_target).and_return(true)
于 2012-10-31T15:23:54.703 回答