我有以下代码:
require 'command'
describe Command do
subject(:command) { described_class.new(input, robotic_rover) }
let(:robotic_rover) do
double(:robotic_rover, position: '0 0 N',
move: '0 1 N',
right_turn: '0 0 E',
left_turn: '0 0 W')
end
describe 'advance command' do
let(:input) { 'M' }
describe 'initialization' do
it 'alters a rovers position' do
expect(command.position_change).to eq robotic_rover.move
end
end
end
describe 'right command' do
let(:input) { 'R' }
describe 'initialization' do
it 'alters a rovers direction' do
expect(command.position_change).to eq robotic_rover.right_turn
end
end
end
describe 'left command' do
let(:input) { 'L' }
describe 'initialization' do
it 'alters the rovers direction' do
expect(command.position_change).to eq robotic_rover.left_turn
end
end
end
end
在每个初始描述块(高级命令,右命令和左命令)中,我尝试使用{{1}定义传递到input
的{{1}}参数的值。 }。
只会发生最后一次测试(左命令),传递和前两次测试(高级命令和右命令)失败:
described_class.new(input, robotic_rover)
如果我从前两个测试中删除了let,那么它们会失败:
let
任何人都可以帮我改变每个描述块的 Failure/Error: expect(command.position_change).to eq robotic_rover.right_turn
expected: "0 0 E"
got: nil
参数的值吗?
守则
使用此代码的意图是将其从多个if中重构出来,但就目前而言,它是我所有的。
Failure/Error: subject(:command) { described_class.new(input, robotic_rover) }
NameError:
undefined local variable or method `input' for #<RSpec::ExampleGroups::Command::AdvanceCommand::Initialization:0x007f90cc14f758>
答案 0 :(得分:1)
我们错过了return
方法中每个条件的#position_change
。
what is the point of return in Ruby?
class Command
attr_reader :input, :robotic_rover
def initialize(input, robotic_rover)
@input = input
@robotic_rover = robotic_rover
end
def position_change
return robotic_rover.move if input == 'M'
return robotic_rover.right_turn if input == 'R'
return robotic_rover.left_turn if input == 'L'
end
end
describe Command do
let(:instance) { described_class.new(input, robotic_rover) }
let(:robotic_rover) do
double(
"RoboticRover",
position: '0 0 N',
move: '0 1 N',
right_turn: '0 0 E',
left_turn: '0 0 W'
)
end
describe '#position_change' do
subject(:position_change) { instance.position_change }
context 'when advance command' do
let(:input) { 'M' }
it 'alters a rovers position' do
expect(position_change).to eq robotic_rover.move
end
end
context 'when right command' do
let(:input) { 'R' }
it 'alters a rovers direction' do
expect(position_change).to eq robotic_rover.right_turn
end
end
context 'when left command' do
let(:input) { 'L' }
it 'alters the rovers direction' do
expect(position_change).to eq robotic_rover.left_turn
end
end
end
end