0
0
Rubyprogramming~30 mins

Let and before hooks in Ruby - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Let and Before Hooks in Ruby Tests
📖 Scenario: You are writing tests for a simple Ruby class that manages a list of tasks. To keep your tests clean and organized, you will use let to define reusable variables and before hooks to set up common test conditions.
🎯 Goal: Build a small test suite using let to create a task list and before hooks to add tasks before each test runs.
📋 What You'll Learn
Create a let variable named task_list that initializes an empty array.
Create a before hook that adds the string 'Buy milk' to task_list.
Write a test that checks if task_list includes 'Buy milk'.
Write a test that adds 'Walk dog' to task_list and checks if both tasks are present.
💡 Why This Matters
🌍 Real World
Using <code>let</code> and <code>before</code> hooks is common in Ruby testing frameworks like RSpec to organize test data and setup steps efficiently.
💼 Career
Understanding these concepts helps you write clean, maintainable tests in Ruby projects, a valuable skill for Ruby developers and QA engineers.
Progress0 / 4 steps
1
Create a let variable for the task list
Write a let block named task_list that returns an empty array [].
Ruby
Need a hint?

Use let(:task_list) { [] } inside the RSpec.describe block.

2
Add a before hook to add a task
Add a before block that adds the string 'Buy milk' to task_list using task_list << 'Buy milk'.
Ruby
Need a hint?

Use before do ... end and inside it add task_list << 'Buy milk'.

3
Write a test to check the initial task
Write an it block with description 'includes Buy milk' that expects task_list to include 'Buy milk' using expect(task_list).to include('Buy milk').
Ruby
Need a hint?

Use it 'includes Buy milk' do ... end and inside use expect(task_list).to include('Buy milk').

4
Write a test to add and check multiple tasks
Write an it block with description 'adds Walk dog and checks both tasks' that adds 'Walk dog' to task_list and expects task_list to include both 'Buy milk' and 'Walk dog' using two expect statements.
Ruby
Need a hint?

Inside the it block, add task_list << 'Walk dog' and two expect lines to check both tasks.