如何存根after_create回调保存!在模特?

时间:2012-10-31 14:34:33

标签: ruby-on-rails ruby ruby-on-rails-3 rspec mocking

我收到以下错误:

输出:

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

1 个答案:

答案 0 :(得分:1)

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

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)