如何创建一个rspec方法存根以允许来自接受哈希键的方法的响应返回其值?
这是我想测试的一行
sub_total = menu.menu_items[item] * quantity
我在rspec中使用这一行作为我的测试存根.
allow(menu).to receive(:menu_items[item]).and_return(2.0)
我的环境设置为ruby 2.2.0和规范3.1.7
但是我继续得到一个
NameError: undefined local variable or method `item'
Ruby代码
def place_order(item,quantity,menu) sub_total = menu.menu_items[item] * quantity @customer_order << [item,sub_total] end
Rspec代码
let(:menu) { double :menu } it "should allow 1 order of beer to placed" do order = Order.new allow(menu).to receive(:menu_items[item]).and_return(2.0) order.place_order(:Beer,1,2.0) expect(order.customer_order).to eq [[:Beer,2.0]] end
失败:
1) Order should allow 1 order of beer to placed Failure/Error: allow(menu).to receive(:menu_items[item]).and_return(2.0) NameError: undefined local variable or method `item' for #<RSpec::ExampleGroups::Order:0x007fbb62917ee8 @__memoized=nil> # ./spec/order_spec.rb:9:in `block (2 levels) in <top (required)>'
我尝试了很多东西,但没有任何效果
allow(menu).to receive(:menu_items).and_return(2.0) allow(menu).to receive(:menu_items).with(item).and_return(2.0) allow(menu).to receive(:menu_items).with("item").and_return(2.0) allow(menu).to receive(:menu_items).with([item]).and_return(2.0)