我需要写一个期望,即在支付系统中创建一个新对象。代码包含order.rb
和order_spec.rb
(Order
类here):
#order.rb
def confirm_order(method_of_payment)
if credit_card_but_products_out_stock?(method_of_payment)
raise "Cannot make credit card payment now, as some products are out of stock"
end
order_total
Payment.new(method_of_payment, self.total)
end
#order_spec.rb
it 'it creates a new payment object if method_of_payment is valid and order.total is > 0' do
order.add_product(product, 3)
order.confirm_order(:credit_card)
#Expect that a new payment object is created.
end
我想了解如何编写适当的规范来测试是否创建了新的Payment对象。我发现来自Semaphore CI的this article很有用,但我不确定解决方案。我很确定我应该创建某种类型的测试双,然后可能是allow(order).to receive(:confirm_order).and_return(#new_object??)
的方法存根。
答案 0 :(得分:12)
如果您正在对Order
课进行单元测试,那么您就不应该嘲笑或抄袭Order
课程。您可以在Payment
类上设置一个期望值来返回一个模拟,然后您可以进一步断言为confirm_order
方法的返回值。
let(:payment) { double :payment }
it "returns a payment" do
expect(Payment).to receive(:new).with(:credit_card).and_return(payment)
order.add_product(product, 3)
expect(order.confirm_order(:credit_card)).to eq(payment)
end
这样,你正在模拟Order
类的依赖关系,而不改变Order
类,这更加安全,因为Order
上的模拟方法很容易创建假阳性测试结果