Bird
0
0

What will be the output of this Ruby code using RSpec mocks?

medium📝 Predict Output Q4 of 15
Ruby - Testing with RSpec and Minitest
What will be the output of this Ruby code using RSpec mocks?
class User
  def name
    'Alice'
  end
end

user = User.new
allow(user).to receive(:name).and_return('Bob')
puts user.name
AAlice
BBob
Cnil
DError
Step-by-Step Solution
Solution:
  1. Step 1: Understand stubbing effect

    The allow(user).to receive(:name).and_return('Bob') replaces name method to return 'Bob'.
  2. Step 2: Determine output of puts user.name

    Since the stub overrides original method, it prints 'Bob'.
  3. Final Answer:

    Bob -> Option B
  4. Quick Check:

    Stubbed method output = Bob [OK]
Quick Trick: Stubbed methods return stub value, not original [OK]
Common Mistakes:
  • Expecting original method output
  • Thinking stub returns nil
  • Assuming code raises error

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes