Testing puts
Outside of a Method
The best way to test the usage of puts
outside the context of a method is to load
the file that will make a call to puts
within an it
block and expect
$stdout
to
receive
a call to puts
with
your desired output.
Example: Testing a CLI Welcome Message
If you were developing a lesson that requires the student's program to print out a message at the start, independent of any initialization method call or object instantiation, as in the example of building a simple program that when run, simply prints `"Hello, World!", the preferred pattern is as follows:
File: spec/hello_world_spec.rb
describe "hello_world.rb" do
it 'prints "Hello, World!" when run or loaded' do
expect($stdout).to receive(:puts).with("Hello, World!")
load './lib/hello_world.rb'
end
end
The solution file would look like:
File: lib/hello_world.rb
Testing puts
within a Method
When the student is required to build a method that upon evocation should output a string, the pattern to use is:
- require the file with the method definition in the test suite,
- set the expectation of
$stdout
to
receive
puts
with
your desired string.
- Evoke the method.
Example: Testing a puts
within a method.
If you were to develop a lesson that required the student to define a method that prints a message dependent upon an argument or external data, use this pattern.
The student must build a say_hello
method that accepts an argument of name
and must output "Hi #{name}!".
File: spec/say_hello_spec.rb
require_relative '../lib/say_hello'
describe "#say_hello" do
it 'prints "Hello <NAME>" for whatever name is passed as an argument' do
expect($stdout).to receive(:puts).with("Hello Kent Beck!")
say_hello("Kent Beck")
end
end
The solution:
File: lib/say_hello.rb
# Build your say_hello method here
def say_hello(name")
puts "Hello #{name}"
end