简体   繁体   English

工厂女孩/ Rspec模型测试的特定协会

[英]Factory Girl/specific association for Rspec model test

I am trying to do this, in spec/models/user_role.spec: 我想在spec / models / user_role.spec中这样做:

role_trainer = FactoryGirl.create(:role_trainer)
user_role = FactoryGirl.build(:user_role, :role => role_trainer)

where I want to specify the specific "role_trainer" in spec/factories/roles.rb: 我想在spec / factories / roles.rb中指定特定的“role_trainer”:

factory :role_trainer, parent: :role do |f|
  f.name "trainer"
end

and then for spec/factories/role_spec.rb, I have: 然后对于spec / factories / role_spec.rb,我有:

FactoryGirl.define do
  factory :user_role do
    user
    role
  end
end

and the models are: 而模型是:

class Role < ActiveRecord::Base
  has_many :user_roles, :dependent => :destroy
  has_many :users, :through => :user_roles

class UserRole < ActiveRecord::Base
  belongs_to :user
  belongs_to :role

That is, in words, I want to determine the "role" of the "user role" that is going to be created. 也就是说,我想确定将要创建的“用户角色”的“角色”。 However, when I do this, I do not find that the "role_trainer" was used as the role, for the user_role. 但是,当我这样做时,我没有发现“role_trainer”被用作user_role的角色。 (Instead, a user_role gets created by the build statement (at the top) which has nothing to do with "trainer".) What is wrong with my setup? (相反,user_role由构建语句(在顶部)创建,与“培训师”无关。)我的设置有什么问题?

Another way to ask it - I need to add multiple roles to a single user, by creating multiple user_roles. 另一种询问方式 - 我需要通过创建多个user_roles为单个用户添加多个角色。 How can I specify the input user, to the FactoryGirl build? 如何指定FactoryGirl构建的输入用户?

I would do something like this: 我会做这样的事情:

FactoryGirl.define do
    factory :role_trainer do
        name 'Trainer'
    end
end

That should do the trick. 这应该够了吧。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM