设计
我有一个用户模型,它通过多态关联属于一个概要文件.我 Select 这种设计的原因可以找到here.总而言之,应用程序中有许多用户的配置文件非常不同.
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
在 Select 了这种设计之后,我很难想出好的测试.使用FactoryGirl和RSpec,我不确定如何以最有效的方式声明关联.
第一次try
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
comments /其他 idea
正如用户规范中的注释所述,使用艺术家似乎很脆弱.如果我的工厂将来发生变化怎么办?
也许我应该用factory_girl callbacks来定义"艺术家用户"和"音乐家用户"?感谢所有的意见.