我正在尝试模仿下面的PriceInspector#get_latest_price
来测试OderForm
。传递了两个命令,因此,我需要在模拟PriceInspector#get_latest_price
时返回两个不同的值。这一切都适用于Supplier
模型(ActiveRecord),但我不能在PriceInspector
类上运行模拟:
# inside the test / example
expect(Supplier).to receive(:find).and_return(supplier_1) # first call, works
expect(PriceInspector).to receive(:get_latest_price).and_return(price_item_1_supplier_1) # returns nil
expect(Supplier).to receive(:find).and_return(supplier_2) # second call, works
expect(PriceInspector).to receive(:get_latest_price).and_return(price_item_2_supplier_1) # returns nil
class OrderForm
include ActiveModel::Model
def initialize(purchaser)
@purchaser = purchaser
end
def submit(orders)
orders.each do |supplier_id, order_items|
@supplier = Organization.find(supplier_id.to_i)
@order_item = OrderItem.save(
price_unit_price: PriceInspector.new(@purchaser).get_latest_price.price_unit_price
)
[...]
end
end
end
class PriceInspector
def initialize(purchaser)
@purchaser = purchaser
end
def get_latest_price
[...]
end
end
修改
以下是基于Bogieman答案的更新测试代码:
before(:each) do
expect(Organization).to receive(:find).and_return(supplier_1, supplier_2)
price_inspector = PriceInspector.new(purchaser, item_1)
PriceInspector.stub(:new).and_return price_inspector
expect(price_inspector).to receive(:get_latest_price).and_return(price_item_1_supplier_1)
expect(price_inspector).to receive(:get_latest_price).and_return(price_item_2_supplier_2)
end
it "saves correct price_unit_price for first OrderItem", :focus do
order_form.submit(params)
expect(OrderItem.first.price_unit_price).to be_within(0.01).of(price_item_1_supplier_1.price_unit_price)
end
答案 0 :(得分:0)
我认为这应该解决实例方法问题,并允许您检查两个不同的退货(假设您传入购买者或双人):
price_inspector = PriceInspector.new(purchaser)
PriceInspector.stub(:new).and_return price_inspector
expect(price_inspector).to receive(:get_latest_price).and_return(price_item_1_supplier_1)
expect(price_inspector).to receive(:get_latest_price).and_return(price_item_2_supplier_1)