Ruby的新手,对不起,如果这很明显。我已经看过here和here了。我正在加载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)>'
先谢谢!!
答案 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