【问题标题】:Expect the creation of a new object期望创建一个新对象
【发布时间】:2016-05-09 14:50:06
【问题描述】:

我需要编写一个期望,即将在支付系统中创建一个新对象。 order.rborder_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??) 的方法存根。

【问题讨论】:

    标签: ruby rspec stub


    【解决方案1】:

    如果您对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 上的模拟方法很容易产生误报测试结果。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-10
      • 1970-01-01
      • 2019-07-19
      • 1970-01-01
      • 2015-06-29
      相关资源
      最近更新 更多