0
0
Rubyprogramming~5 mins

RSpec describe and it blocks in Ruby

Choose your learning style9 modes available
Introduction

RSpec uses describe and it blocks to organize and run tests. They help you check if your code works as expected.

When you want to group related tests for a class or method.
When you want to explain what a piece of code should do in simple terms.
When you want to write small, clear tests that show expected behavior.
When you want to run automated checks to catch mistakes early.
Syntax
Ruby
describe 'Some feature or class' do
  it 'does something expected' do
    # test code here
  end
end

describe groups tests and usually names the feature or class.

it defines a single test example describing expected behavior.

Examples
This tests that adding 2 and 3 equals 5.
Ruby
describe 'Calculator' do
  it 'adds two numbers' do
    expect(2 + 3).to eq(5)
  end
end
This checks that a new array starts empty.
Ruby
describe Array do
  it 'is empty when created' do
    expect(Array.new).to be_empty
  end
end
Sample Program

This program tests two things about the String 'hello': reversing it and checking its length.

Ruby
require 'rspec'

describe 'String' do
  it 'reverses correctly' do
    expect('hello'.reverse).to eq('olleh')
  end

  it 'has correct length' do
    expect('hello'.length).to eq(5)
  end
end
OutputSuccess
Important Notes

Use describe to group tests logically, like chapters in a book.

Use it to write small, clear tests that explain what your code should do.

RSpec output shows which tests passed or failed, helping you find problems fast.

Summary

describe groups related tests.

it defines individual test cases.

Together, they make your tests clear and organized.