Print Function Tests

This is an example of how you can test the output stream of a student defined function.

Ruby makes this super easy with the output matcher.

expect { print 'foo' }.to output('foo').to_stdout

This test makes sure the student's function named prints_name() that takes a name as a parameter and prints "Hello, {name provided}!" to standard output. It assumes the student's file name is example.rb. Replace the require with whatever your student's file name is.

Grading Tests:

require 'rspec'
require 'stringio'
require '/usercode/example'

RSpec.describe "CodingRoomsUnitTests" do

    describe "Run prints_name() with 'Jane'" do
        it "expects output to be 'Hello, Jane!'" do
            expect{prints_name("Jane")}.to output("Hello, Jane!\n").to_stdout
        end
    end

    describe "Run prints_name() with 'Fred'" do
        it "expects output to be 'Hello, Fred!'" do
            expect{prints_name("Fred")}.to output("Hello, Fred!\n").to_stdout
        end
    end

end

Sample Solution:

example.rb
def prints_name(name)
    puts 'Hello, ' + name + "!"
end

prints_name("Jane")

Last updated