期待创建一个新对象

时间:2016-02-01 08:10:56

标签: ruby rspec stub

我需要写一个期望,即在支付系统中创建一个新对象。代码包含order.rborder_spec.rbOrderhere):

#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??)的方法存根。

1 个答案:

答案 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上的模拟方法很容易创建假阳性测试结果