1

私は単純な関連付けを持っています:

class Account < ActiveRecord::Base
  has_many :users

  accepts_nested_attributes_for :users
  validates_presence_of :users
end

class User < ActiveRecord::Base
  belongs_to :account
end

簡単なテストを実行したいだけです。

describe 'a new', Account do
  it 'should be valid' do
    Factory.build(:account).should be_valid
  end
end

工場で:

Factory.define :account do |a|
  a.name                 { Faker::Company.name }
end

Factory.define :user do |u|
  u.association           :account
  u.email                 { Faker::Internet.email }
end

しかし、私はいつもこのエラーに遭遇します:

'a new Account should be valid' FAILED
Expected #<Account id: nil, name: "Baumbach, Gerlach and Murray" > to be valid, but it was not
Errors: Users has to be present

まあ、私は正しい関連付けを設定しましたが、それは機能しません...

あなたの助けのためのthx。

4

1 に答える 1

7

validates_presence_of :usersあなたのAccountモデルで失敗したテストに責任があります。アカウントには少なくとも1人のユーザーが必要なので、アカウントを作成できます。

あなたが本当に何をしたいのかわからないので、この問題を解決するための2つの方法を紹介します。最初のオプションは、ファクトリを変更することです。

Factory.define :account do |a|
  a.name                 { Faker::Company.name }
  a.users                {|u| [u.association(:user)]}
end

Factory.define :user do |u|
  u.email                 { Faker::Internet.email }
end

もう1つの方法は、所属側の関連付けの存在を確認することです。したがって、次のようにモデルを変更する必要があります。

class Account < ActiveRecord::Base
  has_many :users

  accepts_nested_attributes_for :users
end


class User < ActiveRecord::Base
  belongs_to :account
  validates_presence_of :account
end
于 2010-06-24T11:47:49.300 に答える