FactoryGirl和多态关联 [英] FactoryGirl and polymorphic associations
问题描述
我有一个用户模型,该用户模型通过多态关联属于某个配置文件.我选择此设计的原因可以在此处找到.总而言之,该应用程序中有许多用户具有完全不同的配置文件.
I have a User model that belongs to a profile through a polymorphic association. The reason I chose this design can be found here. To summarize, there are many users of the application that have really different profiles.
class User < ActiveRecord::Base
belongs_to :profile, :dependent => :destroy, :polymorphic => true
end
class Artist < ActiveRecord::Base
has_one :user, :as => :profile
end
class Musician < ActiveRecord::Base
has_one :user, :as => :profile
end
选择此设计后,我很难进行良好的测试.使用FactoryGirl和RSpec,我不确定如何以最有效的方式声明关联.
After choosing this design, I'm having a hard time coming up with good tests. Using FactoryGirl and RSpec, I'm not sure how to declare the association the most efficient way.
factories.rb
Factory.define :user do |f|
# ... attributes on the user
# this creates a dependency on the artist factory
f.association :profile, :factory => :artist
end
Factory.define :artist do |a|
# ... attributes for the artist profile
end
user_spec.rb
it "should destroy a users profile when the user is destroyed" do
# using the class Artist seems wrong to me, what if I change my factories?
user = Factory(:user)
profile = user.profile
lambda {
user.destroy
}.should change(Artist, :count).by(-1)
end
评论/其他想法
如用户规范注释中所述,使用Artist似乎很脆弱.如果我的工厂将来发生变化该怎么办?
Comments / other thoughts
As mentioned in the comments in the user spec, using Artist seems brittle. What if my factories change in the future?
也许我应该使用 factory_girl回调并进行定义艺术家用户"和音乐家用户"?感谢所有输入.
Maybe I should use factory_girl callbacks and define an "artist user" and "musician user"? All input is appreciated.
推荐答案
Factory_Girl回调将使生活更加轻松.这样的事情怎么样?
Factory_Girl callbacks would make life much easier. How about something like this?
Factory.define :user do |user|
#attributes for user
end
Factory.define :artist do |artist|
#attributes for artist
artist.after_create {|a| Factory(:user, :profile => a)}
end
Factory.define :musician do |musician|
#attributes for musician
musician.after_create {|m| Factory(:user, :profile => m)}
end
这篇关于FactoryGirl和多态关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!