Rspec报错:预期抛出“No bikes available”异常但未触发,求解决
Hey there! No need to apologize at all—we all start somewhere with RSpec and test-driven development. Let's break down how to get your test passing by implementing the right logic in your DockingStation class.
The Problem
Your test expects release_bike to raise the error "No bikes available" when the docking station only has broken bikes, but right now your business code doesn't check for available (unbroken) bikes before trying to release one.
Step-by-Step Solution
First, let's make sure your Bike class properly tracks whether it's broken (you might already have this, but let's confirm):
class Bike attr_reader :broken def initialize @broken = false end def report_broken @broken = true end # Helper method to check bike's broken status def broken? @broken end end
Now, update your DockingStation class to handle checking for available bikes in the release_bike method:
class DockingStation def initialize @bikes = [] # Store all docked bikes in this array end def dock(bike) @bikes << bike end def release_bike # Filter to get only unbroken, usable bikes available_bikes = @bikes.select { |bike| !bike.broken? } if available_bikes.empty? # Raise the exact error your test is expecting raise 'No bikes available' else # Remove and return the first available bike (adjust this logic if you need different behavior) @bikes.delete(available_bikes.first) end end end
Why This Works
- When you dock a broken bike (like in your test),
available_bikeswill be an empty array. - The method checks for this empty state and raises the "No bikes available" error—exactly what your RSpec test is looking for.
- If there are unbroken bikes present, it will release the first one (you can tweak this to release the most recently docked bike or another logic if needed).
Now when you run your RSpec test, it should pass because the exception is raised as expected!
内容的提问来源于stack exchange,提问作者PaulM

