jeudi 19 février 2015

FactoryGirl belongs_to with Seeded association

I have a UserType object that ideally is seeded in the DB and remains static:



{id: 1, name: 'Individual'}, {id: 2, name: 'Group'}, {id: 3, name: 'Admin'}

class UserType < ActiveRecord::Base
attr_accessible :name
has_many :users
end
class User < ActiveRecord::Base
attr_accessible :email, :first_name
belongs_to :user_type
end


In testing, I simply want to create an admin user that has its user_type_id field set to 3 when created, and for the UserType.all to have those three items. I've tried a number of things, but here's where I'm at:



FactoryGirl.define do
factory :user_type do
id 1
name "Individual"
description "An individual account (B2C)"

trait :group do
after(:create) do |user_type|
id 2
name "Group Leader"
description "A leader/manager of group visits"
end
end
trait :admin do
after(:create) do |user_type|
id 3
name "Administrative"
description = "A user of the Enrollment Generator"
end
end
end
end

FactoryGirl.define do
factory :user do
first_name 'TestUser'
email { Faker::Internet.email }

user_type

trait :admin do
after(:create) do |user|
admin_user_type = UserType.where(id: 3).first
admin_user_type = create(:user_type, :admin) unless admin_user_type
user_type admin_user_type
end
end

end


And my test in spec/features/sessions/admin_sign_in_spec.rb:



feature "Admin signing in" do
background do
@institution = create(:institution_with_institutiondomains)
@admin = create(:user, :admin, email: "admin@#{@institution.subdomain}.com")
end

scenario "with correct credentials", focus: true do
binding.pry
@admin.inspect
page.visit get_host_using_subdomain(@institution.subdomain)
within("#login-box") { fill_in t('email'), with: @admin.email }
click_button t('session.admin.sign_in') #the action in signing in here checks that user.user_type_id == 3

expect(page).to have_content "You're signed in!"
end
end


I appreciate any guidance.


Aucun commentaire:

Enregistrer un commentaire