Reputation: 197
I am tasked with applying RSpec to old code that I have written without changing/updating the code (which to me seems contrary to the point of TDD).
Anyway, I am having trouble finding a way of allowing RSpec to access variables which are placed outside of classes and methods.
My original code is a hacky Caesar Cipher:
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("")}"
I'm trying to write my RSpec tests to access the string
, and key
variables in order to run tests on them. However, I'm having trouble finding a way to do so because they are not defined within a method. Nearly all of the RSpec examples I've seen seem show how to access variables within a method:
describe "foo string" do
it "is equal to another string of the same value" do
expect("foo string").to eq("foo string")
end
end
Are there ways to use RSpec to test variables outside of methods/classes? Am I going about this entirely wrong?
Upvotes: 1
Views: 551
Reputation: 13531
You're running into this problem because because your code is procedural. In this particular case the whole script that you posted seems to act as a single function, taking input from STDIN and outputting to STDOUT.
You should be testing the output of the script, not the variables. Ensuring the output is as expected indirectly tests the variables used to test that result any way.
The first approach that comes to mind is to run the script in a sub shell, piping input into it, and verifying the output.
The better solution would be to wrap your code in a method so you can just test that within the rspec script after requiring your script. Then, just test the output of calling the method.
Here's an SO Q on testing procedural code: How does one unit test sections of code that are procedural or event-based
Upvotes: 1