SpicyCode

The ramblings of Chad Humphries

oooh shiny! rspec extensions for activerecord validations

I’m currently in waiting for rubyforge approval limbo for my new rspec extensions project but I figured I would post about it anyway.

Step 1 – Identify something that annoys you

  • In this case repeatedly writing validation specifications

Step 2 – Fix a problem

  • Write gem to package up solution…in this case spicycode_rspec_extensions

Step 3 – Profit?

  • Ok, so no step three, but it sounded good at the time.

So what does it do?

I started out with the simplest cases I was repeating basing it off of David’s excellent post about custom expectation matchers, more will come later. See the awe-inspiring and mind boggling (well, at least mind boggling) examples below. This does require rspec 0.8.2 or above.


context 'A User (when validating)' do
  ...
  setup do
    @user = User.new(valid_user_attributes)
  end

  specify do
    @user.should require_presence_of :first_name
  end

  specify do
    @user.should require_confirmation_of :password
  end
   ...
end

After running you will get output like the following thanks to RSpec’s automatic naming abilities


A User (when validating)
- should validate presence of first_name
- should validate confirmation of password

Finally, if something were to not match it will print out what was wrong with the object (the objects current errors).

Recap?

Well hopefully some of what I said made sense to someone 🙂 I’ll be pushing the gem up to ye olde ‘forge as soon as the project approval comes through.

Advertisements

Written by spicycode

March 19, 2007 at 5:56 pm

Posted in programming

Tagged with , ,

%d bloggers like this: