9

私は2つのモデルを持っています:

# 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, ......>

しかし、これはうまくいきません!ユーザーがいないため、プロファイル モデルが正しくないことがわかります。(ユーザーの前にプロファイルを保存するため、user_id はありません...)

どうすればこれを修正できますか? すべてを試しました.. :( そして、Factory.create(:user) を呼び出す必要があります...

アップデート

この問題を修正しました - 現在以下で動作しています:

# 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
4

1 に答える 1

3

そのように修正します(この投稿で説明されているように)

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

同様にできることは(ユーザーはプロファイルが存在する必要がないため(検証はありません)、2段階の構築を行うことです

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

その後

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

その場合、プロファイルファクトリでユーザーを作成して、1つのステップが必要なだけだと思います

profile = Factory :profile
@user = profile.user

それはそれを行う正しい方法のようですね。

アップデート

(コメントによると)プロファイルの保存を避けるには、Factory.buildを使用してビルドするだけです。

Factory.define :user do |u|
  u.login "test"
  u.after_build { |a| Factory(:profile, :user => a)}    
end
于 2010-09-06T09:01:07.613 に答える