Consider the following Ruby code using RSpec mocks. What will be printed when this code runs?
class User def name "Alice" end end user = User.new allow(user).to receive(:name).and_return("Bob") puts user.name
Think about what allow(...).to receive(...).and_return(...) does to the method.
The allow method replaces the name method on the user object to always return "Bob" instead of the original "Alice".
What error will this Ruby code raise when run?
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)
Check what arguments the stub expects and what arguments are actually passed.
The stub only affects calls to add with arguments 1, 2. Calling add(2, 3) runs the original method, returning 5.
Look at this Ruby code snippet using RSpec mocks. Why does the stub not change the method output?
class Dog def bark "woof" end end dog = Dog.new allow(Dog).to receive(:bark).and_return("meow") puts dog.bark
Think about the difference between stubbing a class method and an instance method.
The stub was set on the class Dog, but bark is an instance method. The stub does not affect the instance dog.
What will this Ruby code print?
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
Look at what receive_message_chain does.
The receive_message_chain stub replaces the chained call car.engine.start to return "silent" instead of calling the real methods.
Given the following Ruby code, what is the value of result after execution?
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]
Remember what the stub changes the method to return.
The stub changes fetch_data to return a hash with status: 404, so result is 404.