4

我已经看过这里这里了。我加载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

4 回答 4

4
require 'factory_girl_rails'
FactoryGirl.factories.clear

这可能会解决您的问题。

于 2013-01-16T11:34:58.250 回答
4

特征应该在工厂内部。在您的代码中,: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
于 2013-01-16T11:48:01.157 回答
1

我看到的问题是您没有一个名为teams.

require 'Faker'
FactoryGirl.define do

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

  factory :team do
   #... more code here as necessary 
  end
end
于 2013-01-17T19:11:26.800 回答
1

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

FactoryGirl.factories.count
FactoryGirl.factories

然后

FactoryGirl.reload
于 2018-09-29T13:20:18.513 回答