The Passionate Craftsman

Ruby, PHP, MySql, Software engineering and more.

Tuesday, 30 November 2010

Bettermeans Introduction

Saturday, 20 November 2010

Test unique values in Rails model with Rspec

I wanted to test 'validates_uniqueness_of' for this model:

class CourseItem < ActiveRecord::Base
validates_presence_of :course_id, :day, :url
validates_uniqueness_of :course_id, :scope => :day,
:message => "- this day has been already created."
end

I tried to create two objects with the same value and I was getting the validetion error when creating the second value, the spec was failing and I did not know you to test it. There is a custom matcher to test the uniqueness of fields and it is available with a gem developed by Bogdan Gusiev. This blog post will help you to get started: http://gusiev.com/2010/06/ultimate-rspec-matcher-to-test-validation/. That gem has other useful matchers too.

I checked that model with the following code:

Labels: , ,