0
0
Rubyprogramming~5 mins

Let and before hooks in Ruby

Choose your learning style9 modes available
Introduction

Let and before hooks help you set up values and actions before running tests. They keep your tests clean and avoid repeating code.

When you want to create a value once and use it in many tests.
When you need to run some setup code before each test runs.
When you want to keep your test code organized and easy to read.
Syntax
Ruby
let(:name) { value }
before do
  # setup code here
end

let defines a value that is created only when needed.

before runs code before each test example.

Examples
This sets number to 5 when used, and prints a message before each test.
Ruby
let(:number) { 5 }

before do
  puts "Starting test"
end
This creates a greeting and sets an instance variable @name before tests.
Ruby
let(:greeting) { "Hello" }

before do
  @name = "Alice"
end
Sample Program

This test shows how let creates a number and before sets a doubled value before each test.

Ruby
require 'rspec'

RSpec.describe 'Let and before example' do
  let(:number) { 10 }

  before do
    @double = number * 2
  end

  it 'uses let to get number' do
    expect(number).to eq(10)
  end

  it 'uses before to set double' do
    expect(@double).to eq(20)
  end
end

# To run this test, save as example_spec.rb and run: rspec example_spec.rb
OutputSuccess
Important Notes

let values are lazy and memoized, so they run only once per test when called.

before hooks run before every test example, so use them for setup tasks.

Summary

let creates reusable values for tests.

before runs setup code before each test.

Both help keep tests clean and avoid repeating code.