如何使用多态关联模拟/存根对象并保存!在回调?

时间:2012-10-08 13:06:30

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

我有以下控制器规格通过。 但我想用mock或stub替换create(:link)对象。 如何绕过after_create回调update_target

现在,当我试图mock_model(Link)时,我收到错误:

当spec尝试创建登陆对象时,

undefined method `save!' for nil:NilClass

describe LandingsController do
  describe "#destroy" do

    before(:each) do
      controller.stub(:current_user).and_return(mock_model(User))
      stub_request(:any, "www.example.com").to_return(status: 200)
      @link = create(:link)
    end

    let(:landing) do 
      create(:landing, target_id: @link.id)
    end

    it "destroys the landing" do
      Landing.should_receive(:find).with(landing.id.to_s).and_return(landing)
      landing.should_receive(:destroy).and_return(true)
      delete :destroy, id: landing.id, format: :json
    end

    it "returns 204" do
      delete :destroy, id: landing.id, format: :json
      response.status.should == 204
    end
  end
end

class Landing < ActiveRecord::Base
  belongs_to :target, polymorphic: true
  ...
  after_create :update_target
  before_destroy :update_target

  def update_target
    self.target.save!
  end
end

# landings_controller.rb
  respond_to :json

  def destroy
    landing = Landing.find(params[:id])
    target = landing.target
    landing.destroy
    target.save!
    respond_with landing
  end

也许我应该模仿着陆对象。但是怎么做呢?

1 个答案:

答案 0 :(得分:0)

确实

let(:landing) do 
  mock(:landing, target_id: @link.id, destroy: true)
end

解决你的问题?