0
0
Rubyprogramming~20 mins

Let and before hooks in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Let and Before Hooks Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of let and before hook variable usage

What is the output of this Ruby RSpec code snippet?

Ruby
RSpec.describe 'Example' do
  let(:number) { 5 }

  before do
    @result = number * 2
  end

  it 'calculates result' do
    puts @result
  end
end
A10
B5
CError: undefined local variable or method `number`
Dnil
Attempts:
2 left
💡 Hint

Remember that let defines a memoized helper method accessible in before blocks.

🧠 Conceptual
intermediate
1:30remaining
Scope of let variables in before hooks

Which statement about let variables and before hooks in RSpec is true?

A<code>let</code> variables are eagerly evaluated before <code>before</code> hooks run.
B<code>let</code> variables are only accessible inside <code>it</code> blocks, not <code>before</code> hooks.
C<code>let</code> variables cannot be accessed inside <code>before</code> hooks.
D<code>let</code> variables are lazily evaluated and can be accessed inside <code>before</code> hooks.
Attempts:
2 left
💡 Hint

Think about when let variables get evaluated.

Predict Output
advanced
2:00remaining
Effect of multiple before hooks on let variable

What will be printed when running this RSpec test?

Ruby
RSpec.describe 'Multiple before hooks' do
  let(:counter) { @count ||= 0; @count += 1 }

  before do
    counter
  end

  before do
    counter
  end

  it 'prints counter value' do
    puts counter
  end
end
A1
B2
C3
DError: undefined method `count` for nil:NilClass
Attempts:
2 left
💡 Hint

Remember that let is memoized per example and evaluated once.

🔧 Debug
advanced
2:00remaining
let declared after before hook

What will this RSpec code produce?

Ruby
RSpec.describe 'Error example' do
  before do
    @value = number * 3
  end

  let(:number) { 4 }

  it 'prints value' do
    puts @value
  end
end
ASyntaxError due to let after before
BNo error, prints 12
CNilClass error when multiplying
DNameError: undefined local variable or method `number`
Attempts:
2 left
💡 Hint

In RSpec, declaration order of let and before does not affect method availability.

🚀 Application
expert
2:30remaining
Predict final value after multiple let and before hooks

Given this RSpec code, what is the final value of @total printed?

Ruby
RSpec.describe 'Complex let and before' do
  let(:base) { 10 }

  before do
    @total = base + 5
  end

  before do
    @total += base
  end

  it 'prints total' do
    puts @total
  end
end
A20
B15
C25
DError: undefined method `base`
Attempts:
2 left
💡 Hint

Think about how let is evaluated and how @total changes in each before block.