validates_uniqueness_of don't work
-
27-09-2019 - |
Question
It's not some kind of synchronization problem I readed before. The code is quite simple. The model:
class User < ActiveRecord::Base
attr_accessor :name, :email
validates_uniqueness_of :email, :on => :create, :message => "must be unique"
end
The rspec test:
require 'spec_helper'
describe User do
before(:each) do
@valid_attributes = {
:name => "Foo Bar",
:email => "foo@bar.com"
}
end
it "should reject duplcate email address" do
User.create!(@valid_attributes)
duplicate_user = User.new(@valid_attributes)
duplicate_user.should_not be_valid
end
end
I run the test, and get error message:
----------------------------
1)
'User should reject duplcate email address' FAILED
expected #<User id: nil, name: nil, email: nil, created_at: nil, updated_at: nil> not to be valid
/Users/mac/workspace/rails_space/uniq/spec/models/user_spec.rb:14:
Finished in 0.067908 seconds
1 example, 1 failure
-----------------------------
I run the script/console, and create two user objects with same email address. It goes fine, no validate message occur, the two objects both have inserted into the table. I don't what's wrong with it.
My rails version is 2.3.8 and rspc is 1.3.0.
Solution
I believe the problem is the attr_accessor
line that you have. If you have those column names, the accessor will override the column name and that is just part of the class and doesn't care about uniqueness. If you are going to have the accessor methods then it needs to get back to the database in some way. If you need to have the accessor, then you need to tie it to the database by calling write_attribute
.
For more information you can see the documentation for "Overwriting default accessors" at http://api.rubyonrails.org/classes/ActiveRecord/Base.html
I hope this helps!
OTHER TIPS
I think the issue is because you are saying:
validates_uniqueness_of :email, :on => :create
User.new may not be triggering this validation. Try calling duplicate_user.save! and see if that throws an error.
You can try like following
attr_accessible :email
validates_uniqueness_of :email, :on => :create, :message => "must be unique"