如何在控制器中存根更新动作?

问题描述 投票:0回答:1

在我的Rails应用中,我在控制器中有两个操作(创建和更新),在某些情况下它们是相似的。这是我的代码:

  def update
    @contract = current_user.contracts.find(params[:id])

    respond_to do |format|
      if @contract.update_attributes(params[:contract]) 
        format.html { redirect_to @contract, notice: 'Contract was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: "edit" }
        format.json { render json: @contract.errors, status: :unprocessable_entity }
      end
    end
  end

此方法的正确条件行之有效,我已经在规范中进行了介绍,但是我无法从该方法中获得错误条件,并且每次我向该方法传递一些属性时,它都会以'true'值进行响应(因为在我的项目中,我没有任何模型验证)。因此,我决定对这种方法的“假”条件进行处理,花了半天时间,但由于缺乏知识而无法做到这一点。请帮我存根或/和模拟此方法以接收错误的值。非常感谢您的建议!

ruby-on-rails rspec
1个回答
0
投票

我猜您正在使用Rspec?

https://relishapp.com/rspec/rspec-mocks/v/2-6/docs/method-stubs/stub-on-any-instance-of-a-class

Contract.any_instance.stub(:update_attributes).and_return(false)

© www.soinside.com 2019 - 2024. All rights reserved.