views:

31

answers:

3

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 => "[email protected]"
        }
     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.

+1  A: 

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.

Toby Hede
no, there is no error throw out.
wupher
and I run the console, it still can save two duplicate email object. The snap pic is here: http://cl.ly/a92100cd98829580d876I have no idea at all about all of this wrong.
wupher
+1  A: 

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!

Geoff Lanotte
Yes, the problem is there! Thank you so much for great help!
wupher
A: 

You can try like following

attr_accessible :email
validates_uniqueness_of :email, :on => :create, :message => "must be unique"
Ramanavel