Ruby on rails 3 FactoryGirl属于种子协会

Ruby on rails 3 FactoryGirl属于种子协会,ruby-on-rails-3,factory-bot,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_accessib

我有一个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
我在spec/features/sessions/admin\u sign\u中的测试在spec.rb中:


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

不管它值多少钱,任何人找到这个答案都可能不喜欢我的答案,但这是唯一对我有用的东西。用户类型在我的测试数据库中是静态的,所以我删除了:user\u type工厂中的特征。相反,我只是直接设置用户类型并调用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
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
    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