DEV Community

Aliya Lewis
Aliya Lewis

Posted on

3

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

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Image of Bright Data

Maintain Seamless Data Collection – No more rotating IPs or server bans.

Avoid detection with our dynamic IP solutions. Perfect for continuous data scraping without interruptions.

Avoid Detection

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay