How do you create an rspec method stub to give a response from a method that accepts a hash key to return its value?
This is the line I want to check
sub_total = menu.menu_items[item] * quantity
and I use this line in rspec, since my test stub is double.
allow(menu).to receive(:menu_items[item]).and_return(2.0)
My env is configured with ruby 2.2.0 and spec 3.1.7
However i keep getting
NameError: undefined local variable or method `item'
Ruby Code
def place_order(item, quantity, menu)
sub_total = menu.menu_items[item] * quantity
@customer_order << [item, quantity, sub_total]
end
Rspec code
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, 1, 2.0]]
end
Failures:
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)>'
I tried a few things but nothing worked
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)
I run my code in irb and I see that it works, but I cannot find a way for my class to return the hash key twice.