如何在RSpec中存根仍然需要从数据库加载的对象? [英] How to stub an object that still has to be loaded from the database in RSpec?

查看:59
本文介绍了如何在RSpec中存根仍然需要从数据库加载的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查对象的关联是否收到某个方法调用.问题是我可以对对象的关联进行存根,但是稍后从数据库中加载关联时,所加载的对象与我的存根对象不是同一"fysical"对象.它具有相同的ID,但不是相同的"fysical"对象,因此存根不再起作用.

I would like to check whether an object's association receives a certain method call. Problem is that I can stub the object's association, but when later on, the association is loaded from the database, the loaded object is not the same "fysical" object as my stubbed object. It has the same ID, but it is not the same "fysical" object, so the stub doesn't work anymore.

我目前所拥有的(并且可行!)

What I currently have is (and this works!)

  it "should register the payment of the invoice if everything ok" do
    invoice = create(:invoice)
    # Dirty trick to get exactly this instance as invoice of the created financial transaction
    FinancialTransaction.any_instance.stubs(:invoice).returns(invoice)
    invoice.expects(:register_payment).with(invoice.derived_total_cost)
    post :create, :financial_transaction => attributes_for(:financial_transaction, invoice: invoice, amount: invoice.derived_total_cost)
  end 

在第二行保证"中,我将得到相同的fysical对象.这行得通,但是我认为这是肮脏"的解决方案,因为我必须对FinancialTransaction.any_instance进行存根,而实际上我应该对尚未存在的金融交易进行存根.

where the second line "guarantees" that I will get the same fysical object. This works, but I consider it a "dirty" solution, as I have to stub FinancialTransaction.any_instance, where in fact I should stub the not-yet-existing financial transaction.

我想拥有一种写类似的东西的方式

What I would like to have is a way to write something like

  FinancialTransaction.instance_with_id(id).expects(:register_payment)

问题是:这怎么办?

推荐答案

我终于如下解决了此问题

I finally solved this as follows

  let!(:invoice) { create(:invoice) }
  let!(:financial_transaction) { create(:financial_transaction, invoice: invoice) }

  before(:each) do
    FinancialTransaction.stubs(:new).returns(financial_transaction)
  end

  it "should register payment of the invoice if everything ok" do
    invoice.expects(:register_payment).with(invoice.derived_total_cost)
    post :create, :financial_transaction => attributes_for(:financial_transaction, invoice: invoice, amount: invoice.derived_total_cost)
  end

这样,我可以控制正在使用的关联发票,因此,也可以将期望立即绑定到该发票上

This way I can control the associated invoice being used, and as such, can also bind the expectation immediately to this invoice

这篇关于如何在RSpec中存根仍然需要从数据库加载的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆