FactoryGirl - 工厂未注册

时间:2013-01-16 11:27:31

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

Ruby的新手,对不起,如果这很明显。我已经看过herehere了。我正在加载factory_girl_rails

我认为它必定是语法错误,但经过一个小时的头部刮擦后,真的无法修复它。有人可以帮忙吗? :)

这是我的工厂:

require 'Faker'

FactoryGirl.define do

  factory :user do
    name { Faker::Name.name }
    email { Faker::Internet.email }
    password { Faker::Lorem.characters 12 }
  end

  trait :with_teams do
    ignore do
      number_of_teams 5
    end

    after :create do |user, evaluator|
      FactoryGirl.create_list :team, evaluator.number_of_teams, :user => user
    end
  end

end

以下是相关规范:

require 'spec_helper'

describe User do
  # This works fine
  it "can create a team" do
    user = FactoryGirl.create :user
    team = user.teams.create

    team.class.should == Team
  end

  # The marked line throws argument error
  it "can have many teams" do
    user = FactoryGirl.create :user, :with_teams, :number_of_teams => 10 # <---
    user.teams.length.should == 10
  end
end

这是我从运行规范中得到的错误:

    Failures:

      1) User can have many teams
         Failure/Error: user = FactoryGirl.create :user, :with_teams, :number_of_teams => 10
         ArgumentError:
           Factory not registered: User
         # ./spec/factories/users.rb:19:in `block (3 levels) in <top (required)>'
         # ./spec/models/user_spec.rb:34:in `block (2 levels) in <top (required)>'

先谢谢!!

4 个答案:

答案 0 :(得分:3)

require 'factory_girl_rails'
FactoryGirl.factories.clear

这可能会解决您的问题。

答案 1 :(得分:3)

特征应该在工厂内部。在您的代码中,:user工厂和:with_teams特征无关。

require 'Faker'

FactoryGirl.define do

  factory :user do
    name { Faker::Name.name }
    email { Faker::Internet.email }
    password { Faker::Lorem.characters 12 }

    trait :with_teams do
      ignore do
        number_of_teams 5
      end

      after :create do |user, evaluator|
        FactoryGirl.create_list :team, evaluator.number_of_teams, :user => user
      end
    end
  end
end

答案 2 :(得分:0)

我看到的问题是您没有名为teams的工厂。

require 'Faker'
FactoryGirl.define do

  factory :user do
  team
   #.... your code here
  end

  factory :team do
   #... more code here as necessary 
  end
end

答案 3 :(得分:0)

正如wintondeshong在此处的评论中所说-您可能应该重新加载工厂,但是之前您可以检查工厂是否存在:

FactoryGirl.factories.count
FactoryGirl.factories

然后

FactoryGirl.reload