[Updated on 2/25]

Have you seen this show up in your specs?

specify "should be empty" do
  @group.should be_empty
end

As of rev 1519, RSpec will now take (almost) all of the stock expectations and auto-generate spec names for you. So this:

context "A Group" do
  ...
  specify do
    @group.should be_empty
  end
end

A Group
- should be empty

This works for all of the standard expectations except those that take blocks, which would result in names like “should satisfy block”, which doesn’t seem that helpful.

Custom Expectation Matchers

Getting this to work w/ your custom matchers is a snap. Just implement #to_s in the matcher to return a String with everything after “should ” or “should not ”. For example, Equal#to_s in RSpec looks like this:

def description
  "equal #{@expected.inspect}"
end

So the following specs:

specify do
  result.should equal(3)
end

specify do result.should_not equal("this string") end

would result in the following output:

- should equal(3)
- should not equal(\"this string\")

6 Responses to “generated spec names keep specs DRYer”

  1. nicholas a. evans Says:

    That’s wonderful! I was giving a quick demo of rspec on rails just last night, and some people commented on how the DSL of rspec read the exact same as the specify string.

  2. Jay Fields Says:

    David, Looks very good, and feels like the closest I’m going to get to my dream ‘expect’ syntax.

    <p>Good work.</p>
    
  3. Yurii Rashkovskii Says:

    What about something like

     
    gem 'activesupport'
    require 'active_support'

    class Spec::Matchers::Be def description "be #{@comparison ? @comparison : nil}#{@expected} #{@args.to_sentence}" end end

    A bit more on this there:

    <p>http://blog.railsware.com/2007/3/2/rspec-generated-spec-name-for-be</p>
    
  4. David Chelimsky Says:

    Yurii – sounds good – wanna submit a patch?

  5. Yurii Rashkovskii Says:

    David,

    <p>Yes, I&#8217;m thinking about submitting this as patch. Let me try to get how can I accomplish this in the simplest manner.</p>
    
  6. Yurii Rashkovskii Says:

    Ok, first attempt is sent to Rubyforge Tracker.