Testing the Waters with RSpec (Part 2)

aliyalewis profile image Aliya Lewis ・2 min read

So the past couple of weeks I've been in the interview process for a company that I'm really interested in. For their technical assessment, I had to create a CLI app in Ruby using the Google Books API and of course, write some tests. In this blog, I'll go over one of the tests that I found to be the most fun, but I want to note that the application I wrote did not use Rails, it is purely Ruby.

Testing User Input

Here I have a method that takes in user input, checks if it's valid and returns that input:

Alt Text

And here I have a test for that method:

Alt Text

'rl = ReadingList.new' is creating a copy of the application to run inside the test.

'number = rl.save_book' runs #save_book and saves the result of that (@book_number) to the variable 'number'.

'allow($stdin).to receive(:gets).and_return(3)
expect(number).to eq(3)' takes in user input with the expectation that the user types the number 3. If the number 3 is not typed, the test will fail.

Run The Test

To run the test in the terminal, you type rspec with a space after followed by the file path. For me that looked like:

rspec spec/testing/ReadingListCLI_spec.rb


I found this test to be the most interesting because it requires that the tester actually type exactly what the test is expecting in order to pass. The first time I ran the test I thought it was broken because it presented me with what I would see running the application - "If you would like to save any of these books to your reading list please select the number of the book."

That's it for this post but stay tuned for more! If you know of a better way or a different way to test user input let me know in the comments.


Posted on by:

aliyalewis profile

Aliya Lewis


A new fish in the sea of software engineering.


markdown guide