设计

我有一个用户模型,它通过多态关联属于一个概要文件.我 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来定义"艺术家用户"和"音乐家用户"?感谢所有的意见.

推荐答案

工厂女孩的回访会让生活更轻松.像这样的怎么样?

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

Ruby-on-rails相关问答推荐

我可以向 erb 变量插值添加一个类吗?

如何在生成的 HTML 本身中显示部分名称

如何创建一个融合了另外两个记录的 FactoryBot 工厂?

Restful Rails 编辑与更新

来自控制台的 ActionCable.server.broadcast

Rails 将字符串与视图中的变量连接的最佳方法

使用 RSpec 和 Capybara (Rails) 测试重定向

如何在我的 rails 应用程序中测试 ActiveRecord::RecordNotFound?

如何为 Rails SimpleForm Select 框设置默认 Select 值

Rails:仅当值存在时如何验证格式?

Rails - 如何在 f.submit 上放置确认弹出窗口?

如何在 Rails 中验证日期以使其在今天之后?

RubyMine - 关闭在空行中间单击的功能

Rails 5:重命名表迁移

控制器 helper_method

Rails HABTM - 正确删除关联

如何仅使用 PostgreSQL 创建简单的模糊搜索?

你如何undo撤消Bundle 安装 --without

Rails:弃用警告:您没有设置 config.secret_key_base

将数组传递到 hidden_​​field ROR