Factory_girl association with specific values

Hope this should be simple: I have a User model and a Role model. Factories for each.

When I create a User using FG, I want to assign a specific role. Cant seem to figure out how to do this, getting errors like: uninitialized constant SysadminRole for doing things this way:

Factory.define :user do |u|
u.practice_id { |a| a.association(:practice).id }
u.password ‘password1’
u.password_confirmation ‘password1’
u.role { |a| a.association(:sysadmin_role) }
end

Factory.define :sysadmin_role do |f|
f.name ‘sysadmin’
end

Thanks,

David

Since your model is called role and not sysadmin_role, you need to let FactoryGirl know. Otherwise it will use its convention of constantizing the symbol after “define” to determine the model to call.

Factory.define :sysadmin_role, :class => “Role” do |f|

Also good to know is that if you want to use factories for roles that have some fields in common and others that are specific, that you can use this:

Factory.define :role do |f|

f.common_field “foobar”

f.name “guest”

end

Factory.define :sysadmin_role, :parent => :role do |f|

f.name “sysadmin”

end

Factory.define :moderator_role, :parent => :role do |f|

f.name “moderator”

end

Best regards

Peter De Berdt

Hope this should be simple: I have a User model and a Role model.
Factories for each.

When I create a User using FG, I want to assign a specific role.
Cant seem to figure out how to do this, getting errors like:
uninitialized constant SysadminRole for doing things this way:

Factory.define :user do |u|
  u.practice_id { |a| a.association(:practice).id }
  u.password 'password1'
  u.password_confirmation 'password1'
  u.role { |a| a.association(:sysadmin_role) }
end

Factory.define :sysadmin_role do |f|
  f.name 'sysadmin'
end

Since your model is called role and not sysadmin_role, you need to let
FactoryGirl know. Otherwise it will use its convention of
constantizing the symbol after "define" to determine the model to call.

Factory.define :sysadmin_role, :class => "Role" do |f|

Also good to know is that if you want to use factories for roles that
have some fields in common and others that are specific, that you can
use this:

Factory.define :role do |f|
    f.common_field "foobar"
    f.name "guest"
end

Factory.define :sysadmin_role, :parent => :role do |f|
   f.name "sysadmin"
end

Factory.define :moderator_role, :parent => :role do |f|
   f.name "moderator"
end

Best regards

Peter De Berdt

--
You received this message because you are subscribed to the Google Groups
"Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to
rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en.

Thanks Peter, that makes a lot of sense and worked perfectly!