【问题标题】:Is it the correct way to implement belongs_to relation with factory girl?这是与工厂女孩实现belongs_to关系的正确方法吗?
【发布时间】:2013-08-24 00:58:43
【问题描述】:

我有一个非常简单的模型。一个用户有一个 role_id,它依赖于一个角色表(id、name)和一个角色引用。

我想在我的 rspec 测试中创建任何类型的用户,使用工厂女孩。

我的第一个想法是这样的

factory :role do
  name "guest"
  factory :role_admin do
    name "admin"
  end
  factory :role_supervisor do
    name "supervisor"
  end
  etc... I have a lot a different roles
end



factory :user do
  email
  password '123456'
  password_confirmation '123456'
  association :role, factory: :role

  factory :admin do
    association :role, factory: :role_admin
  end
  factory :supervisor do
    association :role, factory: :role_supervisor
  end
  etc... I have a lot a different roles
end

在我的模型中,我有一个简单的方法:

def is(role_name) 
  return self.role.name == role_name
end

这是正确的做法吗?我真的需要为这个角色创建一个工厂吗? 我可以为每个角色的工厂女孩​​中的这个功能制作一个存根吗?

我对所有这些测试内容都很陌生,谢谢。

【问题讨论】:

  • 您的role 表除了id 和名称之外还有其他内容吗?如果不是,我建议您查看 Single Table Inheritance,它可以让您为每个角色创建一个类。
  • 目前只有 id 和 role(我需要一个角色表,因为角色与其他表中的不同模型/动作相关联)。但我的问题更多与工厂女孩的实施有关。单表继承可以帮助我吗?
  • 不,一点也不,它不会帮助你干燥你的工厂,我只是建议你看看它,以防它可能适合你对以下开发的需求:)
  • 好的,谢谢,无论如何都可以使用

标签: ruby-on-rails testing rspec factory-bot


【解决方案1】:

工厂应该反映您的模型。

class User
  has_many :products
end

class Product
  belongs_to :user
end

factory :user do
  products
end

factory :product do
end

如果你想有特殊情况(了解你的情况下的角色)你可以定义traits:

factory :user do

  traits :admin do
  end

  factory :admin_user, traits: [:admin]

end

更多关于特质的信息here。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多