工厂女孩:具有 validates_presence_of Accepts_nested_attributes_for 的关联问题测试模型
我有一个简单的关联:
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
好吧,我设置了正确的关联,但它不起作用......
谢谢你的帮助。
i have a simple associations:
class Account < ActiveRecord::Base
has_many :users
accepts_nested_attributes_for :users
validates_presence_of :users
end
and
class User < ActiveRecord::Base
belongs_to :account
end
i just want to run a simple test:
describe 'a new', Account do
it 'should be valid' do
Factory.build(:account).should be_valid
end
end
with the factories:
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
but i always run into this error:
'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
well, i setup the correct associations, but it doesn't work...
thx for your help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Account
模型中的validates_presence_of :users
是测试失败的原因。您的帐户中至少需要一名用户,以便可以创建它。我不确定你真正想做什么,所以我给你两种方法来解决这个问题。第一个选项是更改您的工厂:
另一种方法是检查所属方是否存在关联。所以你需要像这样改变你的模型:
validates_presence_of :users
in yourAccount
model is responsible for the failing test. You need at least one user in your Account, so it can be created.I'm not sure what you really want to do, so I'm giving you two ways to solve this Problem. The first option is to change your factory:
Another way is to check the presence of the association on the belongs to side. So you need to change your models like this: