RSpec for User Input

I have been practicing writing tests more often. For this, I am using RSpec. The other day I wanted to write tests for a method that required a user’s input but I was not sure how to do it.

This is the method I wrote (I wrapped it in a class):

class Birthday
 def is_it_your_birthday?
  today ="%m/%d")
  puts "When is your birthday (mm/dd)?"
  puts gets.chomp == today ? "Happy Birthday!" : "It is just another day,then."


As you can see, this method requires the user to enter a date in a month/day format and if the date s/he inputs matches today’s date it will prompt the string “Happy Birthday!” to the console.

I had no idea how to test the ruby “gets” method so I did what anyone in my situation would: Googled it.

I found the RSpec documentation and learned about many things that Rspec is able to do. But most importantly about how I could test the snippet of code above.

These are the tests I wrote after my research:

describe '#is_it_your_birthday?' do 
    it "should return \"Happy Birthday\" if user ipunt date matches today's date" do 
      date =
      date.stub(:gets) {"%m/%d")}
      expect(date.is_it_your_birthday?).to eq(puts "Happy Birthday!")

    it "should return \"It is just another day then.\" if user input date does not match today's date" do 
      date =
      date.stub!(:gets) {"%m/%d").succ}
      expect(date.is_it_your_birthday?).to eq(puts "It is just another day, then.")


I stubbed Kernel#gets .stub!(:gets) to perform the task I wanted and mocked the user generated response in the block one example is {"%m/%d")}.

These tests worked just fine for me. It is the first time I created a test for the gets method. I wonder how would other people do it. If you have an better way to do it, please let me know by leaving your comment below.

Happy testing for all.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s