RSpec Stubbing服务对象方法

时间:2017-02-28 23:33:54

标签: ruby-on-rails rspec

我遇到了从AR对象中删除对服务对象(QuickbooksService)的调用的问题。据我所知,该方法应该正确存根并返回我指定的值,但是当我运行规范时,我可以看到被调用的方法并且失败。

这是我测试对象的类定义。

class Order < ActiveRecord::Base
  def create_invoice
    QuickbooksService.new(:estimate).create_invoice(arg1, arg2, arg3)
  end
end

来自order_spec

describe("#create_invoice") do
  expect(QuickbooksService.new(:estimate)).to receive(:create_invoice).and_return(1)
end

我也试过

allow(QuickbooksService.new(:estimate)).to receive(:form_invoice_create).with(anything()).and_return(1)

因此,不是返回1,而是在QuickbooksService内执行create_invoice方法。任何见解都将不胜感激!

3 个答案:

答案 0 :(得分:0)

问题是你在对它进行实例化时allow(QuickbooksService.new(:estimate)).to receive(:form_invoice_create).with(anything()).and_return(1)

试试这个:

allow_any_instance_of(QuickbooksService).to receive(:form_invoice_create).with(anything()).and_return(1)

答案 1 :(得分:0)

您遇到的问题是您正在查找单独的实例。即,当您定义期望时,您告诉它期望特定实例接收对该方法的调用,但是当执行代码时,它正在创建不同的实例。您需要做的是允许任何实例接收方法调用。像allow_any_instance_of(QuickbooksService).to receive(:invoice_create)这样的东西会起作用,但是创建一个双精度语更好,例如:

let(:quickbooks_service) { instance_double(QuickbooksService) }

describe("#create_invoice") do
  before { allow(quickbooks_service).to receive(:create_invoice).and_return(1) }

  it "Creates quickbook invoice" do
    order.create_invoice
    expect(quickbooks_service).to have_received(:create_invoice)
  end
end

请参阅:https://relishapp.com/rspec/rspec-mocks/docs

答案 2 :(得分:0)

在学习rspec模拟和存根时发现了这一点。在Nicholas.V的回答1上,我们也不需要这样做

QuickbooksService.stub(:new).and_return(quickbooks_service)

在致电order.create_invoice之前?