Testing the Waters with RSpec (Part 2)

aliyalewis

Aliya Lewis

Posted on November 23, 2019

Testing the Waters with RSpec (Part 2)

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

Thoughts

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.

Resources

💖 💪 🙅 🚩
aliyalewis
Aliya Lewis

Posted on November 23, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

#Writing Tests for a Ruby Application
testing #Writing Tests for a Ruby Application

September 28, 2021

Testing the Waters with RSpec (Part 2)
testing Testing the Waters with RSpec (Part 2)

November 23, 2019

Testing the Waters with RSpec (Part 1)