it_only: running a single example in RSpec


Sometimes you want to focus on just one example in your RSpec file. I had to do this quite often in the last 3 days and I got tired of commenting out stuff back and forth. So, I give you “it_only” example.

module Spec
  module DSL
    module BehaviourEval
      module ModuleMethods
        def it(description = :__generate_description, opts = {}, &block)
          return if @it_only_found
          examples << Example.new(description, opts, &block)
        end

        # Same as +it+ only blocks all other examples making this the
        # only example that would run.
        def it_only(description = :__generate_description, opts = {}, &block)
          @it_only_found = true
          @examples = [Example.new(description, opts, &block)]
        end
      end
    end
  end
end

Drop this into your spec_helper.rb and now if you want to focus on a single example, just make it “it_only” instead of “it“.

Information and Links

Join the fray by commenting, tracking what others have to say, or linking to it from your blog.


Other Posts
Morning Brew #83
Morning Brew #82

Write a Comment

Take a moment to comment and tell us what you think. Some basic HTML is allowed for formatting.

Reader Comments

Cheers Alex, great idea!!!
However, there is tiny syntax error in the line:
examples

Mmmm my original comment has not been published very well, the incorrect line is number 7: remove the space in “

thnx, wordpress always messes the double angled brackets up :S

You can also use the command line (spec) with the -e option. For example spec -e “should assign bar” spec/foo.spec will run the
it “should assign bar” do
#…
end
spec.