开发者

factory girl - Given Project, how to make permissions? Associations?

I have the following models:

Users (id)
Project (id, name)
Roles (id, title)
Permissions (user_id, role_id, project_id)

With Factory Girl I want to make a factory which includes 2 users, 1 project, and permissions associating the 2 users to the project.

Here's what I have so far:

Factory.define :user do |user|
  user.fname                  "James"
  user.lname                  "Bond"
  user.email                  "james.bond@intuit.com"
  user.password               "password"
  user.password_confirmation  "password"
end

Factory.define :project do |project|
  project.name              "myproject"
  project.private_email     "myproject"
  project.user_id do
    (User.find_by_email('james.bond@intuit.com')).id
  end
  project.instance_id do
    (User.find_by_email('james.bond@intuit.com')).instance_id
  end

  project.permissions {|permissions| [permissions.association(:permission)] }

end


开发者_开发问答Factory.define :permission do |permission|
  permission.role_id         1
  permission.creator_id do
    (User.find_by_email('james.bond@intuit.com')).id
  end  
  permission.user_id do
    (User.find_by_email('james.bond@intuit.com')).id
  end
  permission.project_id do
    (Project.find_by_name('myProject')).id
  end


end

But this errors with:

Failure/Error: @project = Factory(:project) RuntimeError: Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id

I'm new to factory girl, am I doing this right? Thanks


You want to take advantage of the association method to associate models with another.

You would do something like:

 project.user {|i| i.association(:user)}

 permission.creator {|i| i.association(:user)}
 permission.project {|i| i.association(:project)}

etc.

An example of this:

Factory.define :user do |u|
  u.sequence(:email) { |n| "mike#{n}@awesome.com"}
  u.password "funnyguy1"
  u.password_confirmation {|u| u.password }
 end

Factory.define :profile do |p|
  p.sequence(:username) { |n| "madmike#{n}"}
  p.user {|i| i.association(:user)}
end

You would do something like this, for example:

Factory.define :permission do |permission|
  permission.role_id         1
  permission.creator {|i| i.association(:user)}
  permission.user {|i| i.association(:user)}
  permission.project {|i| i.association(:project)}
end

I would suggest reading the github page for FactoryGirl:

https://github.com/thoughtbot/factory_girl

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜