0
0
Rubyprogramming~20 mins

Mocking and stubbing in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Mocking and Stubbing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this Ruby mocking code?

Consider the following Ruby code using RSpec mocks. What will be printed when this code runs?

Ruby
class User
  def name
    "Alice"
  end
end

user = User.new
allow(user).to receive(:name).and_return("Bob")
puts user.name
AAlice
BRuntimeError
Cnil
DBob
Attempts:
2 left
💡 Hint

Think about what allow(...).to receive(...).and_return(...) does to the method.

Predict Output
intermediate
2:00remaining
What error does this Ruby stub code raise?

What error will this Ruby code raise when run?

Ruby
class Calculator
  def add(a, b)
    a + b
  end
end

calc = Calculator.new
allow(calc).to receive(:add).with(1, 2).and_return(5)
puts calc.add(2, 3)
A5
B5.0
C3
DRSpec::Mocks::MockExpectationError
Attempts:
2 left
💡 Hint

Check what arguments the stub expects and what arguments are actually passed.

🔧 Debug
advanced
2:00remaining
Why does this stub not work as expected?

Look at this Ruby code snippet using RSpec mocks. Why does the stub not change the method output?

Ruby
class Dog
  def bark
    "woof"
  end
end

dog = Dog.new
allow(Dog).to receive(:bark).and_return("meow")
puts dog.bark
ABecause <code>allow</code> was called on the class, not the instance
BBecause <code>allow</code> cannot stub methods that return strings
CBecause <code>dog.bark</code> is a private method
DBecause <code>allow</code> requires a block to work
Attempts:
2 left
💡 Hint

Think about the difference between stubbing a class method and an instance method.

Predict Output
advanced
2:00remaining
What is the output of this chained stub in Ruby?

What will this Ruby code print?

Ruby
class Car
  def engine
    Engine.new
  end
end

class Engine
  def start
    "vroom"
  end
end

car = Car.new
allow(car).to receive_message_chain(:engine, :start).and_return("silent")
puts car.engine.start
Asilent
Bvroom
CNoMethodError
Dnil
Attempts:
2 left
💡 Hint

Look at what receive_message_chain does.

Predict Output
expert
2:00remaining
What is the value of the variable after this stubbed method call?

Given the following Ruby code, what is the value of result after execution?

Ruby
class Service
  def fetch_data
    {status: 200, body: "data"}
  end
end

service = Service.new
allow(service).to receive(:fetch_data).and_return({status: 404, body: "not found"})
result = service.fetch_data[:status]
A200
B404
C"data"
Dnil
Attempts:
2 left
💡 Hint

Remember what the stub changes the method to return.