[rspec-users] Nested model and Factory.build

Adam Wilson lists at ruby-forum.com
Wed Dec 15 20:26:24 EST 2010

I am new to RSpec and BDD, learning it while starting a new project.

I am writing model tests for a user model with a has_one association:

class User < ActiveRecord::Base

  has_one :core_profile
  validates_associated :core_profile, :as => :core_profileable
  accepts_nested_attributes_for : core_profile

  after_initialize :build_associations

  def build_associations
    build_core_profile unless core_profile || !core_profile.valid?


class CoreProfile < ActiveRecord::Base

  attr_accessor :password, :password_confirmation
  attr_accessible :user_name
  attr_protected :hashed_password
  validates :user_name, :presence => true
  validates :first_name, :presence => true
  validates :last_name, :presence => true

  belongs_to :core_profileable, :polymorphic => true


I am using Factory Girl to test model data.
I have been trying to test creation of a Parent. Testing for a valid
Parent and valid CoreProfile work fine, also invalid Parent and valid
CoreProfile... however when I test for valid Parent and invalid
CoreProfile I get an failure do to "Validation failed" - it seems to not
return invalid for the Parent... here is the test in question:

  it "should be invalid :invalid_core_profile_user" do
    user = Factory.build(:invalid_core_profile_user)
    user.core_profile.should_be invalid?

and the Factory definitions:

Factory.define :invalid_core_profile_parent, :class => User do |p|
  p.email 'barry.white at test.com'
  p.phone_number '(925) 555-1212'
  p.association :invalid_core_profile

Factory.define :invalid_core_profile, :class => CoreProfile do |cp|
  cp.first_name  'Barry'
  cp.last_name 'White'
  cp.user_name ''
  cp.password 'password'
  cp.password_confirmation ''

I am assuming that Factory.build(:invalid_core_profile_user) creates the
associated objects first but does not bubble up the validity, just
breaks out with the "Validation failed" message.

Maybe I am doing this wrong  - should User only handle its own
validation and not its associated models? Thing is - the CoreProfile
should only be saved as part of a User, so its important to test them

I have googled high and low and can't seem to find an answer.

Thanks for reading!

Posted via http://www.ruby-forum.com/.

More information about the rspec-users mailing list