无论我的输入是什么,我的rspec测试都会失败。 我正在运行测试以确保输入介于1-4之间 它只在我输入3时才起作用?
require 'order'
describe Order do
it 'gets dish input' do
order = Order.new
allow(order.input).to receive(:gets).and_return(:name)
end
it 'checks input' do
order = Order.new
expect(order.input).to eq (1..4)
end
end
调用order.rb
class Order
def initialize
input
end
def input
puts 'please select the number of your dish'
gets.chomp
end
def valid_range? input
input.to_i.between?(1..4)
end
end
谢谢
答案 0 :(得分:1)
您可以将Order
课程编写为:
class Order
attr_reader :dish_number
def initialize
@dish_number = input.to_i
end
def valid_dish?
dish_number.between?(1, 4)
end
private
def input
puts 'please select the number of your dish'
gets.chomp
end
end
其相应的规范应该是:
require_relative '../order.rb'
describe Order do
it 'gets dish number as input' do
allow_any_instance_of(Order).to receive(:input).and_return("1")
order = Order.new
expect(order.dish_number).to eq(1)
end
it 'checks valid dish' do
allow_any_instance_of(Order).to receive(:input).and_return("1")
order = Order.new
expect(order).to be_valid_dish
end
end
结果是:
[arup@Ruby]$ rspec spec/order_spec.rb
..
Finished in 0.00946 seconds (files took 0.12904 seconds to load)
2 examples, 0 failures
[arup@Ruby]$
正如@myron所说,这是代码的DRY版本:
require_relative '../order.rb'
describe Order do
def new_order(input)
order = Order.new
allow(order).to receive(:input).and_return(input)
order
end
it 'gets dish number as input' do
expect(new_order("1").dish_number).to eq(1)
end
it 'checks valid dish' do
expect(new_order("1")).to be_valid_dish
end
end