gpt4 book ai didi

ruby-on-rails - 工厂女孩 : association problem testing model which has validates_presence_of accepts_nested_attributes_for

转载 作者:太空宇宙 更新时间:2023-11-03 17:19:08 24 4
gpt4 key购买 nike

我有一个简单的联想:

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

好吧,我设置了正确的关联,但它不起作用...

感谢您的帮助。

最佳答案

您的 Account 模型中的

validates_presence_of :users 是测试失败的原因。您的帐户中至少需要一位用户,才能创建。

我不确定你到底想做什么,所以我给你两种方法来解决这个问题。第一个选择是改变你的工厂:

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

另一种方法是检查属于方的关联是否存在。所以你需要像这样改变你的模型:

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

关于ruby-on-rails - 工厂女孩 : association problem testing model which has validates_presence_of accepts_nested_attributes_for,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3109505/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com