设计
我有一个用户模型,它通过多态关联属于一个个人资料。我选择这种设计的原因可以在这里找到。简而言之,该应用程序有许多具有非常不同资料的用户。
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,我不确定最有效的声明关联的方式。
第一次尝试
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时似乎很脆弱。如果我的工厂将来发生了变化怎么办?
也许我应该使用factory_girl callbacks并定义“artist user”和“musician user”?非常感谢您的建议。