has_many关系的工厂女孩错误 [英] Factory Girl error with has_many relationship
问题描述
我有以下工厂:
Factory.define :email do |email|
email.email {"infomcburney.cowan.com"}
end
Factory.define :lead do |lead|
lead.emails {|emails| [emails.association(:email)]}
end
正在为以下类别建模
class Lead < ActiveRecord::Base
has_many :emails
end
class Email < ActiveRecord::Base
belongs_to :lead, :class_name => "Lead", :foreign_key => "lead_id"
end
当我通过应试运行此测试时:
When I run the this test through shoulda:
should "capture emails" do
lead = Factory.build(:lead)
assert_equal(1, lead.emails.size)
end
我收到以下错误:
Factory :: AttributeDefinitionError: 属性已定义:电子邮件
Factory::AttributeDefinitionError: Attribute already defined: emails
我完全坚持这一点,谁能指出我正确的方向.我正在使用factory_girl 1.3.2.
I am completely stuck on this, can anyone point me in the right direction. I am using factory_girl 1.3.2.
推荐答案
我建议不要将has_many关系数据添加到您的工厂.原因是您的牵头工厂现在依赖于填充此关联,并且如果关联更改,它将增加更多的耦合,并可能在将来产生一些混乱.
I would recommend against adding has_many relationship data to your factories. The reason for this is that your lead factory now depends on populating this association and it's adding more coupling and potentially some confusion down the road if the association changes.
如果您想测试这种关系(我建议您这样做),那么有个很棒的宝石,叫做 Shoulda ,它添加了单元测试宏,以确保正确设置关系.我尚未将其与内置的Rails Test :: Unit一起使用,但是RSpec的示例将类似于:
If you want to test this relationship (and I recommend you do), there's a great gem called Shoulda that adds unit test macros to ensure that the relationships are setup right. I haven't used it with the built in Rails Test::Unit, but an RSpec example would look something like:
describe Lead do
it { should have_many(:emails) }
end
如果您真的想测试这种关系,则应在规范中进行.从潜在客户工厂中删除电子邮件关联,并创建潜在客户对象,然后尝试向其传递一些电子邮件对象,如下所示:
If you really want to test this relationship, you should do it in the spec. Remove the emails association from your lead factory and create a lead object and try to pass it a few email objects like so:
lead = Factory.build(:lead)
2.times do { lead.emails << Factory.build(:email, :lead => lead) }
然后它应该与几个电子邮件关联.但是,您应该对ActiveRecord充满信心,并且仅仅测试Rails已经为您做的事情之外的事情.这是Shoulda出现的地方.
Then it should have a couple emails association with it. However, you should put some faith in ActiveRecord and just test things that are above and beyond what Rails is already doing for you. This is where Shoulda comes in.
我对您的电子邮件归属关系的另一条评论.由于您仅使用默认约定,因此rails会知道该怎么做.
Another comment I have is on your Email belongs_to relationship. Since you're just using the default conventions, rails will know what to do.
class Email < ActiveRecord::Base
belongs_to :lead
end
这篇关于has_many关系的工厂女孩错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!