期望对象使用Rspec在控制器中接收方法

时间:2014-11-21 11:42:53

标签: ruby-on-rails rspec

我试图测试在调用控制器的动作时是否调用方法。

describe Admin::CartProductDesignsController, :type => :controller do
  let!(:personalized_cart_product) { create :personalized_cart_product}
  let!(:cart_product_design) { create :cart_product_design, quantity: 100, personalized_cart_product: personalized_cart_product }

  describe "PATCH #update" do
    it "generates the production sheet" do
      expect_any_instance_of(CartProductDesign).to receive(:some_method)
      patch :update, cart_product_design: {quantity: "20"}, cart_product_id: personalized_cart_product.id, id: cart_product_design , format: 'js'
    end
  end
end


class Admin::CartProductDesignsController < Admin::ApplicationController

  inherit_resources
  actions :create, :update, :destroy
  respond_to :html, :js

  def update
    @cart_product_design.some_method
    update! do |success, failure|
      success.html { redirect_to [:admin, @cart_product_design.order] }
      failure.html { redirect_to [:admin, @cart_product_design.order], alert: @cart_product_design.errors.full_messages.first }
    end
  end
end

运行rspec时出现此错误:

 1) Admin::CartProductDesignsController PATCH #update generates the production sheet
     Failure/Error: Unable to find matching line from backtrace
       Exactly one instance should have received the following message(s) but didn't: some_method

为什么失败? 在某种程度上,补丁请求一个黑盒子,它只返回一些价值,并不关心它在里面被调用的内容?

提前致谢

1 个答案:

答案 0 :(得分:1)

@cart_product_design仅由继承的update!方法设置,因此当您在控制器方法的第一个语句中调用nil时,它应为some_method。您的方法真的被称为some_method吗?

要执行您想要执行的操作,请参阅继承资源gem的README并查找此示例:

class ProjectsController < InheritedResources::Base
  def update
    @project = Project.find(params[:id])
    @project.something_special!
    update!
  end
end

顺便说一句,我猜你注意到这个宝石现在已被弃用了。