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 = Date.today.strftime("%m/%d")
puts "When is your birthday (mm/dd)?"
puts gets.chomp == today ? "Happy Birthday!" : "It is just another day,then."
end
end
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 = Birthday.new
date.stub(:gets) {Date.today.strftime("%m/%d")}
expect(date.is_it_your_birthday?).to eq(puts "Happy Birthday!")
end
it "should return \"It is just another day then.\" if user input date does not match today's date" do
date = Birthday.new
date.stub!(:gets) {Date.today.strftime("%m/%d").succ}
expect(date.is_it_your_birthday?).to eq(puts "It is just another day, then.")
end
end
I stubbed Kernel#gets .stub!(:gets)
to perform the task I wanted and mocked the user generated response in the block one example is {Date.today.strftime("%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.