Q:

Model passes validation of :presence => true and still nil in database

user_type is a column in user model and it has to be :presence => true. It rejects in rspec when passing a nil to user_type. However the factory_girl can store a nil user_type into the field with sqlite3. 
Running rails 3.1.0. rspec 2.6.0 and factory_girl 2.1.0
//user model:
  validates :user_type,  :presence => true  

//Factory girl definition:
Factory.define :user do |user|

  user.name                  "Test User"
  user.email                 "test@test.com"
  user.password              "password1"
  user.password_confirmation "password1"
  user.status                "active"
  user.user_type             "employee"

end

Factory.define :user_level do |level|

  level.role                 "sales"
  level.position             "member"
  level.team                 1
  level.association          :user
end

//rspec case: passed
  it "should reject user type nil" do
    user = Factory.build(:user, :user_type => nil)
    user.should_not be_valid  
  end

  it "should take user type 'employee'" do
    user = Factory.build(:user, :user_type => 'employee')
    user.errors[:user_type].should be_empty
    user.should be_valid
  end

Any thoughts? thanks. 

A:

As Michael Hartl pointed out in his excellent Rails tutorial, Factory Girl bypasses attr_accessible in the model. For instance, you can overwrite the "magic" columns using Factory Girl. Perhaps this applies to validations as well?
It seems like it would be better in this case to actually create your user with User.new, since you are testing the process of creation and validation itself.

