[英]RSpec Stubbing Service Object Method
I'm having an issue with stubbing out a call to a service object (QuickbooksService) from an AR object. 我遇到了从AR对象中断对服务对象(QuickbooksService)的调用的问题。 As far as I can tell the method should be stubbed properly and return the value I'm specifying but when I run the spec I can see the method being called and failing.
据我所知,该方法应该正确地存根并返回我指定的值,但是当我运行规范时,我可以看到该方法被调用并失败了。
Here's the class definition of the object I'm testing. 这是我正在测试的对象的类定义。
class Order < ActiveRecord::Base
def create_invoice
QuickbooksService.new(:estimate).create_invoice(arg1, arg2, arg3)
end
end
And from order_spec 并从order_spec
describe("#create_invoice") do
expect(QuickbooksService.new(:estimate)).to receive(:create_invoice).and_return(1)
end
I've also tried 我也尝试过
allow(QuickbooksService.new(:estimate)).to receive(:form_invoice_create).with(anything()).and_return(1)
So instead of returning 1
the create_invoice
method is being executed inside of QuickbooksService. 因此,而不是返回
1
,而是在QuickbooksService内部执行create_invoice
方法。 Any insight would be appreciated! 任何见识将不胜感激!
The problem you are having is that you are stubbing a seperate instance. 您遇到的问题是您正在存根单独的实例。 ie When you define the expectation, you telling it to expect that a particular instance receives a call to the method, but when the code is executed, it is creating a different instance.
即,当您定义期望时,您告诉它期望特定实例接收到对该方法的调用,但是当执行代码时,它正在创建另一个实例。 What you need to do is allow any instance to receive the method call.
您需要做的是允许任何实例接收方法调用。 Something like
allow_any_instance_of(QuickbooksService).to receive(:invoice_create)
will work, but it is much better practice to create a double, something like: 诸如
allow_any_instance_of(QuickbooksService).to receive(:invoice_create)
可以工作,但是创建一个double更好的做法是,例如:
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
See: https://relishapp.com/rspec/rspec-mocks/docs 请参阅: https : //relishapp.com/rspec/rspec-mocks/docs
The problem is that you are instantiating the class while stubbing it allow(QuickbooksService.new(:estimate)).to receive(:form_invoice_create).with(anything()).and_return(1)
问题在于您正在实例化该类,同时将其
allow(QuickbooksService.new(:estimate)).to receive(:form_invoice_create).with(anything()).and_return(1)
Try this: 尝试这个:
allow_any_instance_of(QuickbooksService).to receive(:form_invoice_create).with(anything()).and_return(1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.