【问题标题】:How to use FactoryGirl with a seed.rb file如何将 FactoryGirl 与 seed.rb 文件一起使用
【发布时间】:2015-11-07 01:09:57
【问题描述】:

我的种子文件已加载到我的 test_helper 文件中。当我尝试通过工厂创建角色时,验证失败,因为它已经存在(由于种子文件)。但是,如果我使用在种子中创建的角色在工厂中创建关联角色...我会收到一个错误,因为工厂似乎是在种子文件之前启动的...工厂错误是因为它正在寻找的角色没有尚未创建。这很混乱。

此工厂无法通过唯一角色名称验证,因为已通过种子文件创建了角色。

FactoryGirl.define do
  factory :account do
    user
    role
  end
end

此工厂(调用 admin_account 作为关联)出错,因为尚未创建角色。

FactoryGirl.define do
  factory :account do
    user

    trait :admin do
      role Role.find_by_name("admin").id # Role "admin" should exist from the seed
    end

    factory :admin_account, traits: [:admin]
  end
end

因此,如果我不使用种子文件,我的工厂将无法通过唯一性验证。如果我确实使用种子文件,工厂将无法为 nil:NilClass (NoMethodError) 抱怨未定义的方法“id”。

我做错了什么?

【问题讨论】:

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


    【解决方案1】:

    require 'factory_girl_rails' 添加到您的db/seeds.rb 文件中。

    这是一个例子:

    db/seeds.rb

    require 'factory_girl_rails'
    
    puts 'Creating Roles.'
    %w(guest user admin super-admin super-duper-admin).each do |role|
      FactoryGirl.create(:role, name: role)
    end
    
    FactoryGirl.create(:user)
    
    FactoryGirl.create(:admin_user)
    

    spec/factories/roles.rb

    FactoryGirl.define do
      factory :role do
        name { "role_#{rand(9999)}" }
    
        factory :guest_role, parent: :role do
          name 'guest'
        end
    
        factory :user_role, parent: :role do
          name 'user'
        end
    
        factory :admin_role, parent: :role do
          name 'admin'
        end
      end
    end
    

    spec/factories/users.rb

    FactoryGirl.define do
      factory :user do
        email 'user@example.com'
    
        factory :admin_user, parent: :user do
          email 'admin@example.com'
          after(:create) {|user| user.add_role(:admin)}
        end
      end
    end
    

    【讨论】:

    • 你只是在seeds.rb中创建记录,根本没有使用FactoryGirl。
    • 是的。使用工厂。
    【解决方案2】:

    回答我自己的问题(有点)。不要使用工厂女孩。注意全部大写。我知道这引起了很多争论……但是,我不得不说放弃 Factory Girl,放弃 RSpec……并使用 Fixtures 进行 MiniTest 使我的测试环境更易于管理和使用。我喜欢固定装置! 我知道这并不完全是这个问题的答案......但是,希望如果有人发现这篇文章,我可能会激励他们简化他们的应用程序并使用 rails 为您提供的内容。

    【讨论】:

    • chrs - 但是您能否详细说明为什么夹具比 factory_bot 和 rspec 更好/更容易?我现在正在使用这两种方法,这就是我问的原因 - 有兴趣听听您的意见吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-24
    • 1970-01-01
    • 2013-06-26
    • 1970-01-01
    • 2013-04-05
    • 2012-05-20
    • 2015-01-24
    相关资源
    最近更新 更多