FactoryGirl属于Seeded协会

时间:2015-02-19 18:33:17

标签: ruby-on-rails-3 factory-bot

我有一个UserType对象,理想情况下是在DB中播种并保持静态:

{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

在测试中,我只想创建一个admin用户,其user_type_id字段在创建时设置为3,而UserType.all则包含这三个项目。我已经尝试了很多东西,但是我在这里:

FactoryGirl.define do
  factory :user_type do
    id 1
    name "Individual"

    trait :group do
      after(:create) do |user_type|
        id 2
        name "Group Leader"
      end
    end
    trait :admin do
      after(:create) do |user_type|
        id 3
        name "Administrative"
      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

我在 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

在许多情况下,特别是在我创建多个用户的测试中,我会在第一个id:1个人身上收到MySQL重复错误。我很感激任何指导。

1 个答案:

答案 0 :(得分:0)

对于它的价值,任何发现这一点的人都可能不喜欢我的回答,但这是唯一对我有用的东西。 UserTypes在我的测试数据库中是静态的,因此我删除了:user_type工厂中的特征。相反,我只是直接设置user_type_id并在其上调用save。如果没有保存,则更改不会保留到我的@admin变量。使用DatabaseCleaner在测试之间清理测试数据,只留下我的user_types表。

    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                    
            user.user_type_id = 3
user.save #without this, the change won't persist 
          end
        end

      end
    end