我想创建一个方法,接受用户输入。它将用户输入变成一个整数,然后从用户输入中减去一个。如果用户输入不是数字,它也会返回-1。但是测试会引发错误。 Ruby方法无法通过Rspec测试
describe '#input_to_index' do
it 'converts a user_input to an integer' do
user_input = "1"
expect(input_to_index(user_input)).to be_a(Fixnum)
end
it 'subtracts 1 from the user_input' do
user_input = "6"
expect(input_to_index(user_input)).to be(5)
end
it 'returns -1 for strings without integers' do
user_input = "invalid"
expect(input_to_index(user_input)).to be(-1)
end
end
这里是我的方法:
def input_to_index(user_input)
user_input = user_input.to_i
user_input = user_input - 1
return -1 if !user_input.is_a? Numeric
end
后'USER_INPUT = user_input.to_i',它总是*一个'整数',因此是'数字'。因此'if'分支永远不会匹配。你总是去'else'分支。 –
我想说的是,在你检查它的地方,'user_input'永远不会是'Numeric'。因此没有必要检查。 –
这是正确的。 – Asdrubal