Topic: validates uniqueness of username [SOLVED]

i am trying to be a good developer and write test for my application.

i have this simple test that checks that 2 usernames cant be the same

it "validates uniqueness of username attribue" do
    user =
      username: 'moisesZaragoza',
      password: 'something',
      password_confirmation: 'something'
    user2 =
      username: 'moisesZaragoza',
      password: 'something',
      password_confirmation: 'something'
    user2.should have(1).errors_on(:username)


  1) User validates uniqueness of username attribue
     Failure/Error: user2.should have(1).errors_on(:username)
       expected 1 errors on :username, got 0
     # ./spec/models/user_spec_OLD.rb:72:in `block (2 levels) in <top (required)>'


class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :token_authenticatable, :confirmable,
  # :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  # Setup accessible (or protected) attributes for your model
  attr_accessible :email, :password, :password_confirmation, :remember_me, :username, :first_name, :last_name, :account_id
  # attr_accessible :title, :body
  belongs_to :account
  validates_uniqueness_of :email, presence: true, :case_sensitive => false
  validates_uniqueness_of :username, presence: true, :case_sensitive => false
  validates :username , :length => { :in => 2..30 }

  validates :first_name, presence: true, :length => { :in => 2..20 }
  validates :last_name, presence: true, :length => { :in => 2..20 }

Last edited by moiseszaragoza (2012-05-24 11:46:25)

Re: validates uniqueness of username [SOLVED]

Call user2.valid? before user2.should have(1).errors_on(:username).  Or you could do user2.should_not be_valid

Re: validates uniqueness of username [SOLVED]

Thanks you so much