期望对象在使用 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

为什么会失败?补丁请求是否是一个黑盒,它只返回一些值而不关心它在里面叫什么?

提前致谢

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

若要执行要执行的操作,请参阅继承的资源 gem 的自述文件并查找以下示例:

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

顺便说一句,我假设您注意到此宝石现已弃用。

最新更新