0
0
Rubyprogramming~20 mins

Test doubles concept in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Test Doubles Mastery
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 test double example?

Consider this Ruby code using RSpec test doubles. What will be printed?

Ruby
require 'rspec/mocks/standalone'

user = double('User')
allow(user).to receive(:name).and_return('Alice')

puts user.name
AAlice
Bnil
Cundefined method `name' for #<Double User>
DError: NoMethodError
Attempts:
2 left
💡 Hint

Test doubles can be told to return specific values for methods.

🧠 Conceptual
intermediate
1:30remaining
What is the main purpose of a test double in Ruby testing?

Choose the best description of why test doubles are used in Ruby tests.

ATo speed up the Ruby interpreter during tests
BTo replace real objects with simplified stand-ins to isolate tests
CTo automatically generate test data for database records
DTo log all method calls during test execution
Attempts:
2 left
💡 Hint

Think about how test doubles help focus tests on one part of the code.

🔧 Debug
advanced
2:00remaining
Why does this Ruby test double code raise an error?

Look at this Ruby code snippet using RSpec doubles. What causes the error?

Ruby
require 'rspec/mocks/standalone'

order = double('Order')

puts order.total
AMissing 'require' statement for RSpec doubles
BThe double 'Order' is not created correctly without a block
CThe 'puts' method cannot print double objects
DNo method stub for 'total' was defined, so calling it raises an error
Attempts:
2 left
💡 Hint

Think about what happens when you call a method on a double without stubbing it.

📝 Syntax
advanced
1:30remaining
Which Ruby code correctly creates a test double with a stubbed method?

Choose the option that correctly creates a test double named 'Car' with a method 'start' returning 'vroom'.

Acar = double('Car').stub(:start).and_return('vroom')
Bcar = double('Car') { def start; 'vroom'; end }
Ccar = double('Car', start: 'vroom')
Dcar = double('Car').allow(:start).to_return('vroom')
Attempts:
2 left
💡 Hint

Look for the correct syntax to stub a method when creating a double.

🚀 Application
expert
2:30remaining
How many methods will this Ruby test double respond to?

Given this Ruby code, how many methods will the user double respond to?

Ruby
require 'rspec/mocks/standalone'

user = double('User')
allow(user).to receive(:name).and_return('Bob')
allow(user).to receive(:email).and_return('bob@example.com')

methods = user.methods.select { |m| [:name, :email].include?(m) }
puts methods.size
A2
B0
CAll methods of Object plus :name and :email
DRaises an error because methods is undefined
Attempts:
2 left
💡 Hint

Consider only the methods explicitly stubbed on the double.