Sun11Jul

  1. Shoulda: with vs. without

    ActiveRecord spec without shoulda:

    describe Address do
      let(:address) { Factory.build :valid_address }
      %w(street_address locality region postal_code country).each do |attribute|
        it "is invalid without #{attribute}" do
          address.send "#{attribute}=", nil
          address.should_not be_valid
          address.errors.on(:"#{attribute}").should include "can't be blank"
          address.send "#{attribute}=", 'valid input'
         address.should be_valid
        end
      end
    end
    

    ActiveRecord spec with Shoulda:

    describe Address do
      it { should validate_presence_of :street_address }
      it { should validate_presence_of :locality }
      it { should validate_presence_of :region }
      it { should validate_presence_of :postal_code }
      it { should validate_presence_of :country_name }
    end
    

    Even using a healthy dash of metaprogramming to make the first example as brief as possible, it’s clear shoulda wins hands down for brevity, readability, and concision.

    s