如何在 Factory Girl 中创建与 has_many :through 关系的关联?
在我的模型中,我有以下设置:
class User < ActiveRecord::Base
has_many :assignments
has_many :roles, :through => :assignments
end
class Role < ActiveRecord::Base
has_many :assignments
has_many :users, :through => :assignments
end
class Assignment < ActiveRecord::Base
belongs_to :user
belongs_to :role
attr_accessible :role_id, :user_id
end
在我的factory.rb 文件中,我有:
FactoryGirl.define do
factory :user do
sequence(:username) { |n| "user#{n}" }
email { "#{username}@example.com" }
password 'secret'
password_confirmation 'secret'
factory :admin do
...
end
end
factory :role do
name 'Normal'
value 'normal'
end
factory :assignment do
...
end
end
我正在努力弄清楚如何添加角色, :name => “管理员”,:值=> “admin”,到“user”块内的“admin”工厂,这样我就可以调用
create(:admin)
我的测试并让用户具有管理员角色。
谢谢您的关注。
In my models I have the following setup:
class User < ActiveRecord::Base
has_many :assignments
has_many :roles, :through => :assignments
end
class Role < ActiveRecord::Base
has_many :assignments
has_many :users, :through => :assignments
end
class Assignment < ActiveRecord::Base
belongs_to :user
belongs_to :role
attr_accessible :role_id, :user_id
end
In my factory.rb file I have:
FactoryGirl.define do
factory :user do
sequence(:username) { |n| "user#{n}" }
email { "#{username}@example.com" }
password 'secret'
password_confirmation 'secret'
factory :admin do
...
end
end
factory :role do
name 'Normal'
value 'normal'
end
factory :assignment do
...
end
end
I'm struggling to figure out how I would add a role with, :name => "admin", :value => "admin", to the "admin" factory inside the "user" block so I can call
create(:admin)
in my tests and have a user with the admin role.
Thank you for looking.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对于这样的工厂,您需要使用工厂女孩的回调。
试试这个:
For such a factory you need to use callbacks of factory girl.
Try this:
@kshil 是正确的,但您可以稍微收紧代码并使其更加模块化。
为管理员用户创建第二个
:role
工厂。此外,如果工厂名称与关联名称相同,则可以省略工厂名称。
:assignment
工厂变为:在
:user
工厂内定义:admin_user
工厂,并且不必指定父工厂。您还可能添加两个工厂来定义普通用户和管理员用户。@kshil is correct but you can tighten up the code a little and make it more modular.
Create a second
:role
factory for the admin user.Also, if a factory name is the same as the association name you can leave out the factory name. The
:assignment
factory becomes:Define the
:admin_user
factory inside the:user
factory and you don't have to specify the parent factory. You would also probably to add two factories to define both normal and admin users.