【问题标题】:How to write a Klass.any_instance_with_id(id).expects(:method) in RSpec如何在 RSpec 中编写 Klass.any_instance_with_id(id).expects(:method)
【发布时间】:2014-01-25 11:32:53
【问题描述】:

在使用 RSpec 编写测试时,我经常需要表达类似的东西

Klass.any_instance_with_id(id).expects(:method)

主要原因是在我的测试中,我经常有应该接收该方法调用的对象可用,但由于 ActiveRecord 在从数据库加载具有该 id 的对象时会创建一个不同的实例,我不能把“期望”放在我自己的实例上

有时我可以存根 find 方法以强制 ActiveRecord 加载我的实例,有时我可以存根其他方法,但是拥有“any_instance_with_id”会让生活变得更加轻松......

无法想象我是第一个遇到这个问题的人......所以如果你们中的任何人找到了“解决方法”,我很高兴知道!

说明需求的示例:

控制器规格:

describe 'an authorized email' do
  let(:lead) { create(:lead, status: 'approved') }

  it "should invoice its organisation in case the organisation exceeds its credit limit" do
    lead.organisation.expects :invoice_leads
    get :email
  end
end

控制器:

def email
  leads = Lead.approved

  leads.each do |lead|
    lead.organisation.invoice_leads if lead.organisation.credit_limit_exceeded?
  end

  redirect_to root_path
end

【问题讨论】:

    标签: ruby-on-rails rspec


    【解决方案1】:

    对我来说,你需要它来做规格似乎很奇怪。

    您应该将问题提高一级:当您的应用尝试检索记录时。

    例子:

    #code 
    @user = User.find(session[:user_id])
    
    # spec
    let(:fake_user) { mock_model 'User', method: false }
    
    it 'description' do
      User.should_receive(:find).and_return fake_user
      fake_user.expects(:method)
    
      #...
    end
    

    订单/发票示例:

    let(:order)   { mock_model 'order', invoice: invoice }
    let(:invoice) { mock_model 'Invoice', 'archive!' => false }
    

    【讨论】:

    • 我所说的记录通常是“隐藏”在顶级记录中的关联。我还没有找到等效的“查找”来覆盖以在从数据库加载它们时捕获它们。示例是与发票相关联的订单,当发票本身标记为“平衡”时,应收到消息“归档!”
    • 请显示您的代码和规格 :) 同时我编辑了我的答案
    猜你喜欢
    • 2023-03-20
    • 2017-08-23
    • 1970-01-01
    • 1970-01-01
    • 2017-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-07
    相关资源
    最近更新 更多