0

I am working on a Ruby problem called "Speaking Grandma" where I need to create a method that should should take in a string argument containing a phrase and check to see if the phrase is written in all uppercase: if it isn't, then grandma can't hear you. She should then respond with (return) HUH?! SPEAK UP, SONNY!.

However, if you shout at her (i.e. call the method with a string argument containing a phrase that is all uppercase, then she can hear you (or at least she thinks that she can) and should respond with (return) NO, NOT SINCE 1938!.

I wrote the following code:

def speak_to_grandma(input)
if
  input != input.upcase
  puts 'HUH?! SPEAK UP, SONNY!' 
else
  puts 'NO, NOT SINCE 1938!'
end
end

When I run RSpec, I fail both tests. It gives the following message:

Failure/Error: expect(speak_to_grandma('Hi Nana, how are you?')).to eq 'HUH?! SPEAK UP, SONNY!'
       expected: "HUH?! SPEAK UP, SONNY!"
            got: nil 

and

 Failure/Error: expect(speak_to_grandma('WHAT DID YOU EAT TODAY?')).to eq "NO,          NOT SINCE 1938!"
       expected: "NO, NOT SINCE 1938!"
            got: nil
       (compared using ==)

I have no idea what I am doing wrong here. Can anyone help?

p4sh4
  • 3,292
  • 1
  • 20
  • 33
TechRav
  • 9
  • 1
  • `speak_to_grandma` isn't returning the expected string, it's printing it. `eq` from RSpec is checking the return value which is going to be nil (because that's what `puts` returns). Take a look at [this documentation](http://www.rubydoc.info/github/rspec/rspec-expectations/RSpec/Matchers#output-instance_method) which can be used to check against expected output. – Peter Huene Nov 30 '15 at 04:22
  • Wow! Thanks! Just needed that little guidance from you and I have figured it out! Awesome! – TechRav Nov 30 '15 at 04:28

1 Answers1

3

The speak_to_grandma method returns the return value of the puts method, being the last line in the method. The return value of puts is nil(Why are all my puts returning =>nil?)

The eq method in Rspec checks the return value of a method. The string is output to the screen with puts, but the return value is nil, and that's what Rspec is checking for.

If you remove puts, the tests should pass, because the string will be the return value of the method. But the correct way would be to test it with the output method in Rspec. Write your test like this:

expect { speak_to_grandma('WHAT DID YOU EAT TODAY?') }.to output("NO, NOT SINCE 1938!").to_stdout
Community
  • 1
  • 1
p4sh4
  • 3,292
  • 1
  • 20
  • 33