Ruby 和 Rspec 模拟哈希

Ruby and Rspec mocking a hash

我创建了一种方法,可以将哈希中的所有值对相加。 该方法有效,但正在努力为其模拟测试。

方法在这里,

class Basket

  attr_reader :order, :total

  def initialize
    @order = {}
    @total = total
  end

  def add
    @total = (@order.map { |x,y| y}).sum.round(10)
  end
end

还有测试,我尝试模拟哈希。

order = {"pizza" => 12.99}
let(:basket) { double(order: order, total: nil, add: nil)}

describe '#add' do
    it 'calculates the total price for an order' do
      basket.add
      expect(basket.total).to eq 12.99
    end
  end

以及失败消息。

expected: 12.99
     got: nil

(compared using ==)

正如我提到的,class 中的方法正在运行。只需要我的测试通过! 任何帮助都会很棒。

我认为您正在寻找 partial double 来存根某些功能,同时允许此对象仍然正常运行。

类似于以下内容:

class Basket
  attr_reader :order, :total
  def initialize
    @order = {}
  end
  def add
    @total = order.map { |_,y| y}.sum # note no @ in front of order
  end
end

RSpec.describe Basket do 

  let(:order)  { {"pizza" => 12.99} }
  let(:basket) { Basket.new}

  describe '#add' do
    it 'calculates the total price for an order' do
      allow(basket).to receive(:order).and_return(order)
      basket.add # we have to call add or total will be nil
      expect(basket.total).to eq 12.99
    end
  end
end

这里我们使用真实的 Basket 但是当那个篮子调用 #order 时我们存根响应。

Example

还有大量其他清理工作需要完成,因为现在无法在购物篮中下订单,如果您不致电 #add,那么 total 将会nil 即使 order