0
0
Rubyprogramming~30 mins

RSpec expectations and matchers in Ruby - Mini Project: Build & Apply

Choose your learning style9 modes available
RSpec Expectations and Matchers
📖 Scenario: You are writing tests for a simple Ruby method that calculates the square of a number. Testing helps you check if your code works as expected before using it in real projects.
🎯 Goal: Build a basic RSpec test suite using expectations and matchers to verify that a square method returns correct results for given inputs.
📋 What You'll Learn
Create a Ruby method called square that returns the square of a number
Write an RSpec test file with a describe block for the square method
Use expect with the eq matcher to check the output for input 3
Add a test using the be_a matcher to confirm the output is an Integer
Use the not_to matcher to verify the output is not zero for input 5
💡 Why This Matters
🌍 Real World
Testing code with RSpec is common in Ruby projects to catch bugs early and ensure code quality.
💼 Career
Many Ruby developer jobs require writing and understanding RSpec tests to maintain reliable software.
Progress0 / 4 steps
1
Create the square method
Write a Ruby method called square that takes one parameter n and returns n * n.
Ruby
Need a hint?

Define a method with def and return the number multiplied by itself.

2
Set up RSpec describe block
Write an RSpec describe block for the square method. Inside it, write an it block with description 'returns the square of a number'.
Ruby
Need a hint?

Use RSpec.describe 'square' do and inside it an it block with the given description.

3
Add expectation with eq matcher
Inside the it block, write an expectation using expect(square(3)) and the eq(9) matcher to check the output.
Ruby
Need a hint?

Use expect with the method call and to eq(9) to check the result.

4
Add more matchers and print test results
Add two more tests inside the describe block: one using expect(square(4)).to be_a(Integer) to check the output type, and another using expect(square(5)).not_to eq(0) to confirm the output is not zero. Then run the tests to see the results.
Ruby
Need a hint?

Use be_a(Integer) matcher to check type and not_to eq(0) to check value is not zero.