Ruby RSpec-处理方法/类之外的变量
我的任务是对我编写的旧代码应用RSpec,而不更改/更新代码(在我看来,这与TDD的观点相反) 无论如何,我很难找到允许RSpec访问类和方法之外的变量的方法 我的原始密码是一个骇人的凯撒密码:Ruby RSpec-处理方法/类之外的变量,ruby,rspec,Ruby,Rspec,我的任务是对我编写的旧代码应用RSpec,而不更改/更新代码(在我看来,这与TDD的观点相反) 无论如何,我很难找到允许RSpec访问类和方法之外的变量的方法 我的原始密码是一个骇人的凯撒密码: puts 'Please enter your string to be coded' string = gets.chomp.split("") puts 'Please enter your number key' key = gets.chomp.to_i if (ke
puts 'Please enter your string to be coded'
string = gets.chomp.split("")
puts 'Please enter your number key'
key = gets.chomp.to_i
if (key > 26)
key = key % 26
end
string.map! do |i|
i.ord
end
string.map! {|i| i = i + key}.map! {|i|
if (i > 122)
then i = i - 26
elsif (90 < i && i < 97)
then i = i - 26
elsif (i > 96 && (i - key) < 91 && (i - key) > 64)
then i = i - 26
elsif (i < 65 )
then i = 32
else
i
end
}
string.map! do |i|
i.chr
end
puts "Your coded word is #{string.join("")}"
有没有办法使用RSpec测试方法/类之外的变量?我是不是完全错了 您遇到这个问题是因为您的代码是程序性的。在这个特殊的例子中,您发布的整个脚本似乎作为一个函数,从STDIN获取输入并输出到STDOUT 您应该测试脚本的输出,而不是变量。确保输出如预期的那样,以任何方式间接测试用于测试该结果的变量 想到的第一种方法是在子shell中运行脚本,将输入导入其中,并验证输出 更好的解决方案是将代码包装在一个方法中,这样您就可以在需要脚本后在rspec脚本中测试它。然后,只需测试调用该方法的输出
这里有一个关于测试过程代码的问题:这是某种分配吗?这看起来像是出于教育目的而做的事情。我敢打赌,将原始代码分解成方法并用RSpec测试它们是最好的选择。最好的方法是将代码放入类中并用方法包装。测试起来会容易得多,特别是如果您想使用“白盒”方法并测试代码中变量的值。但是如果你真的不能修改代码,我会选择纯黑盒。只需发送几个不同的标准输入,并检查标准输出。这里是指针:STDOUT:STDIN:@Yes是的,这是一个任务。我同意你的看法,这似乎更符合RSpec和良好代码重构的精神。
describe "foo string" do
it "is equal to another string of the same value" do
expect("foo string").to eq("foo string")
end
end