Stop RSpec on the first failure with the --fail-fast command line option

By on (last updated on )

Imagine you’re running your whole RSpec test suite and the first or second test fails. You have about two hundred tests to go, but you want to dive in and fix that first failure right away. You’d probably interrupt the run to get the failure details to go fix them, right?

While this works most of the time (you might get some problems interrupting the run when using Selenium) wouldn’t it be awesome if RSpec could automatically stop and output when running into the first failure?

Stop RSpec on the first failure with the --fail-fast command line option

The fail_fast configuration

I started poking around in the RSpec source and accidentally stumbled on RSpec’s generated documentation on Relish, where I found the fail_fast configuration option that got introduced in rspec-core 2.0.0.rc. It actually does exactly what I wanted to achieve.

The fail_fast option will cause RSpec to immediately stop running your specs and output the failure details whenever it fails for the first time, giving you a nice speed boost when trying to fix some spec fails.

RSpec.configure do |c|
  c.fail_fast = true
end

The --fail-fast command line option

Since you probably still want to run your whole spec suite without using the fail_fast option from time to time, setting it in spec/spec_helper.rb isn’t really a great option. So I added a command line option so you can use it whenever you want.

$ rspec spec --fail-fast
..F

Failures:

  1) Fuubar when it is created does not start the bar until the formatter is started
    Failure/Error: expect(formatter.progress).to be_started
      expected `#<ProgressBar:0/0>.started?` to return true, got nil
    # ./spec/fuubar_spec.rb:64:in `block (3 levels) in <top (required)>'

Finished in 0.02256 seconds (files took 0.15578 seconds to load)
3 examples, 1 failure

Failed examples:

rspec ./spec/fuubar_spec.rb:63 # Fuubar when it is created does not start the bar until the formatter is started

The --fail-fast option was released yesterday as a part of RSpec 2.1, so don’t forget to update.