我有以下代码:
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
在每个初始描述 block (高级命令、右命令和左命令)中,我试图定义传递给 described_class.new(input , robotic_rover)
和 let
。
发生的情况是只有最后一个测试(左命令)通过,而前两个测试(高级命令和右命令)失败并显示:
Failure/Error: expect(command.position_change).to eq robotic_rover.right_turn
expected: "0 0 E"
got: nil
如果我从前两个测试中的每一个中删除 let,那么它们会失败:
Failure/Error: subject(:command) { described_class.new(input, robotic_rover) }
NameError:
undefined local variable or method `input' for #<RSpec::ExampleGroups::Command::AdvanceCommand::Initialization:0x007f90cc14f758>
谁能帮我更改每个描述 block 的 initialize
参数的值?
代码
此代码的目的是从多个 if 中重构它,但现在,这就是我所拥有的。
class Command
attr_reader :input, :robotic_rover
def initialize(input, robotic_rover)
@input = input
@robotic_rover = robotic_rover
end
def position_change
robotic_rover.move if input == 'M'
robotic_rover.right_turn if input == 'R'
robotic_rover.left_turn if input == 'L'
end
end
最佳答案
我们在 #position_change
方法中缺少每个条件的 return
。
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
关于ruby - 更改 described_class.new 参数的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39077913/