Input / Output Tests
This is an example of how you can mock input values and test the output stream of student code.
The student must use the puts function to prompt the user for their first name, then use gets.chomp to collect the first name without a newline attached, and again for their last name. Then, print Hello, firstname lastname! including the person's first and last name.
Sample Run:
1
What is your first name?
2
Jane
3
What is your last name?
4
Doe
5
Hello, Jane Doe!
Copied!
It assumes the student's file name is example.rb. Replace the require with whatever your student's file name is.
Note: This code converts the output to all lowercase and removes spaces to compare against the correct value.

Grading Tests:

1
require 'rspec'
2
require 'stringio'
3
​
4
student_code = File.read("/usercode/example.rb")
5
new_student_code = student_code.gsub(" gets", " $stdin.gets")
6
File.open("/usercode/example.rb", "w") do |f|
7
f.write(new_student_code)
8
end
9
​
10
RSpec.describe "CodingRoomsUnitTests" do
11
​
12
describe 'Giving code Jane and Doe as inputs' do
13
it "output should equal 'Hello, Jane Doe!'" do
14
input = StringIO.new()
15
output = StringIO.new()
16
input.puts "Jane"
17
input.puts "Doe"
18
input.rewind
19
$stdin = input
20
$stdout = output
21
load '/usercode/example.rb'
22
expect(output.string).to include("Hello, Jane Doe!")
23
$stdin = STDIN
24
$stdout = STDOUT
25
end
26
end
27
​
28
describe 'Giving code Joe and Mazzone as inputs' do
29
it "output should equal 'Hello, Joe Mazzone!'" do
30
input = StringIO.new()
31
output = StringIO.new()
32
input.puts "Joe"
33
input.puts "Mazzone"
34
input.rewind
35
$stdin = input
36
$stdout = output
37
load '/usercode/example.rb'
38
expect(output.string).to include("Hello, Joe Mazzone!")
39
$stdin = STDIN
40
$stdout = STDOUT
41
end
42
end
43
​
44
end
Copied!
RSpec, the unit testing framework we are using, seems to have a hard time replacing the standard input stream. That is why you see this code at the beginning of our test file.
1
student_code = File.read("/usercode/example.rb")
2
new_student_code = student_code.gsub(" gets", " $stdin.gets")
3
File.open("/usercode/example.rb", "w") do |f|
4
f.write(new_student_code)
5
end
Copied!
To allow RSpec to load a new standard input stream, we need to replace all instances of gets and use $stdin.gets. Instead of teaching students to not use gets and always use $stdin.gets, we can simply add the above code to replace all instances of gets with $stdin.gets.
Note: On Coding Rooms, the testing instance copies the student code so the above doesn't actually modify the student submission, it just changes it for the test. Other platforms or your local may behave differently.

Sample Solution:

example.rb
1
puts 'What is your first name?'
2
firstname = gets.chomp
3
​
4
puts 'What is your last name?'
5
lastname = gets.chomp
6
​
7
puts 'Hello, ' + firstname + " " + lastname + "!"
Copied!
Export as PDF
Copy link
Contents