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:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
describe CourseItem do | |
# check uniqueness using this matcher https://github.com/bogdan/accept_values_for | |
context "should create one item per day and per course only" do | |
before do | |
CourseItem.create! :day => 1, :course_id => 1, :url => '/courses/index.html' | |
end | |
it { should_not accept_values_for(:day => 1, :course_id => 1) } | |
end | |
end |
0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home