You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rspec报错:预期抛出“No bikes available”异常但未触发,求解决

Fixing the RSpec Error: No Exception Raised When Releasing Bikes

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_bikes will 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 22:48:16