我想检查一个对象的关联是否收到某个方法调用。问题是我可以存根对象的关联,但是当稍后从数据库加载关联时,加载的对象与我的存根对象不是同一个“物理”对象。它具有相同的 ID,但它不是相同的“物理”对象,因此存根不再起作用。
我目前拥有的是(并且这有效!)
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
第二行“保证”我会得到相同的物理对象。这可行,但我认为这是一个“肮脏”的解决方案,因为我必须存根 FinancialTransaction.any_instance,实际上我应该存根尚不存在的金融交易。
我想要的是一种写类似东西的方法
FinancialTransaction.instance_with_id(id).expects(:register_payment)
问题是:如何做到这一点?
我最终解决了这个问题如下
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
这样我就可以控制正在使用的关联发票,因此也可以立即将期望绑定到该发票
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)