RSpec Generated Spec Name for "be"

Posted by yrashk on March 02, 2007

I was talking about generated spec names few hours ago. Although, I’ve found that they simply don’t work properly with “be” matchers. I’ve tried to produce a quick workaround for this. That’s what I’ve created:

 
gem 'activesupport'
require 'active_support'

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

Now I can run following code:

 
context "Random number in 0..100 range" do 

  setup do
    @random_number = rand(100)
  end

  specify do
    @random_number.should be < 100
  end

  specify do
    @random_number.should be >= 0
  end

  specify do
    @random_number.should_not be_nil
  end

  specify do
    @random_number.should be_between(0,100)
  end

  specify do
    @random_number.should_not be_between(100,200)
  end

end
 

and get this as output:

Random number in 0..100 range
- should be < 100 
- should be >= 0 
- should not be nil 
- should be between 0 and 100
- should not be between 100 and 200

Update: This improvement was included into rspec trunk

Comments
  1. Michael KlishinMarch 02, 2007 @ 03:06 PM

    The same way should work for custom matchers, shouldn’t it? If so then this RSpec release is just amazing.

  2. Dmytro ShteflyukMarch 08, 2007 @ 01:40 PM

    I don’t like “should be operator value syntax”, because it does not work with .

     
    context 'Invalid specification: 200' do
      setup do
        @number = 200
      end
    
      specify do
        @number.should be == 100
      end
    end
     
    

    I’m always using should , should >= and so.