代码之家  ›  专栏  ›  技术社区  ›  BvuRVKyUVlViVIc7

工厂女孩有一个关系,证明存在

  •  9
  • BvuRVKyUVlViVIc7  · 技术社区  · 16 年前

    我有两种型号:

    # user.rb
    class User < ActiveRecord::Base
      has_one :profile, :dependent => :destroy
    end
    
    # profile.rb
    class Profile < ActiveRecord::Base
      belongs_to :user
      validates_presence_of :user
    end
    
    # user_factory.rb
    Factory.define :user do |u|
      u.login "test"
      u.association :profile
    end
    

    我想这样做:

    @user = Factory(:user)
    => #<User id: 88,....>
    @user.profile
    => #<Profile id:123, user_id:88, ......>
    
    @user = Factory.build(:user)
    => #<User id: nil,....>
    @user.profile
    => #<Profile id:nil, user_id:nil, ......>
    

    但这行不通! 它告诉我,我的配置文件模型是不正确的,因为没有用户!(它在用户之前保存配置文件,因此没有用户id…)

    我需要打电话工厂.创建(:用户)。。。

    更新

    # user_factory.rb
    Factory.define :user do |u|
      u.profile { Factory.build(:profile)}
    end
    
    # user.rb
    class User < ActiveRecord::Base
      has_one :profile, :dependent => :destroy, :inverse_of => :user
    end
    
    # profile.rb
    class Profile < ActiveRecord::Base
      belongs_to :user
      validates_presence_of :user
    end
    
    1 回复  |  直到 15 年前
        1
  •  3
  •   Community Mohan Dere    9 年前

    把它修好( as explained in this post

    Factory.define :user do |u|
      u.login "test"
      u.profile { |p| p.association(:profile) }
    end
    

    你也可以做的是(作为一个用户不需要一个概要文件存在(没有对它的验证)做两步构造

    Factory.define :user do |u|
      u.login "test"
    end
    

    然后

    profile = Factory :profile
    user = Factory :user, :profile => profile
    

    profile = Factory :profile
    @user = profile.user
    

    Factory.define :user do |u|
      u.login "test"
      u.after_build { |a| Factory(:profile, :user => a)}    
    end