鉴于对TDD的所有炒作,我决定是时候深入挖掘并将其添加到要研究的事物列表中。我遇到了一个问题,我100%肯定这只是我在RSpec测试中出错的一个功能。我仍然是RSpec的新手,所以我很难搞清楚......我的方法很好用,但方法的测试没有。
方法代码(我知道我可以重构这个A LOT。这是我之前写的第一个Ruby程序之一,它解释了丑陋)
def caesar_cipher(string,offset)
string=string.to_s
offset=offset.to_i
cipher=[]
string.each_byte do |i|
#capital letters
if (i>64 && i<91)
if (i+offset)>90
cipher << (i+offset-26).chr
else
cipher << (i+offset).chr
end
elsif (i>96 && i<123)
if (i+offset)>122
cipher << (i+offset-26).chr
else
cipher << (i+offset).chr
end
else
cipher << i.chr
end
end
cipher=cipher.join('')
puts "The encrypted string is: #{cipher}"
end
puts "Enter the string you'd like to encrypt"
string=gets.chomp
puts "Enter the offset you'd like to use"
offset=gets.chomp
caesar_cipher(string,offset)
测试代码(仅针对一个通用案例,所有小写输入)
require './caesarCipher.rb'
describe "caesar_cipher" do
it 'should handle all lower case input' do
caesar_cipher("abcdefg", 3).should == "defghij"
end
end
方法输出:
$ ruby caesarCipher.rb
Enter the string you'd like to encrypt
abcdefg
Enter the offset you'd like to use
3
The encrypted string is: defghij
测试输出:
$ rspec spec/caesar_cipher_spec.rb
Enter the string you'd like to encrypt
Enter the offset you'd like to use
The encrypted string is: require './caesarCipher.rb'
The encrypted string is: defghij
F
Failures:
1) caesar_cipher should handle all lower case input
Failure/Error: caesar_cipher("abcdefg", 3).should == "defghij"
expected: "defghij"
got: nil (using ==)
# ./spec/caesar_cipher_spec.rb:5:in `block (2 levels) in <top (required)>'
Finished in 0.00542 seconds (files took 0.14863 seconds to load)
1 example, 1 failure
Failed examples:
rspec ./spec/caesar_cipher_spec.rb:4 # caesar_cipher should handle all lower case input
有关测试失败原因的任何帮助?从输出来看,它看起来像是在测试中运行了两次或者什么。
答案 0 :(得分:2)
在此行之后添加cipher
或return cipher
puts "The encrypted string is: #{cipher}"
它应该可行
为了解释给定的修复,方法中的最后一个表达式是返回值。您已将值传递给STDOUT但未作为方法的返回值,因此RSpec失败。