1

我在 Rails 应用程序之外编写 FactoryGirl。我在 support/factories.rb 中创建了一个工厂

require 'factory_girl'

FactoryGirl.define do
  factory :user do
    first_name { Faker::Name.first_name }
    last_name { Faker::Name.last_name }
    email { Faker::Internet.email }
    password { "a123456Q" }
    address { Faker::Address.street_name }
    mobile {"1234567890"}
    country {"india"}
    login {Faker::Name.first_name}
  end
end

在 env.rb 中建立连接

ActiveRecord::Base.establish_connection(
  :adapter => 'mysql2',
  :host => 'localhost',
  :database => 'consultancy',
  :username => "root",
  :password => "")

puts ActiveRecord::Base.connection.execute("select * from users")

这里放回<Mysql2::Result:0xa932d80>

当运行命令FactoryGirl.factories它返回

#<FactoryGirl::Registry:0xa39d118 @name="Factory", @items={:user=>#<FactoryGirl::Factory:0xb2e82d0 @name=:user, @parent=nil, @aliases=[], @class_name=nil, @definition=#<FactoryGirl::Definition:0xb000f68 @declarations=#<FactoryGirl::DeclarationList:0xb000f90 @declarations=[#<FactoryGirl::Declaration::Dynamic:0xa66b098 @name=:first_name, @ignored=false, @block=#<Proc:0xa66b070@/home/vijay_demo_project/bank_cucumber/features/support/factories.rb:5>>, #<FactoryGirl::Declaration::Dynamic:0x9ac5f7c @name=:last_name, @ignored=false, @block=#<Proc:0x9ac5cd4@/home/vijay_demo_project/bank_cucumber/features/support/factories.rb:6>>, #<FactoryGirl::Declaration::Dynamic:0x9ef23fc @name=:email, @ignored=false, @block=#<Proc:0x9ef2168@/home/vijay_demo_project/bank_cucumber/features/support/factories.rb:7>>, #<FactoryGirl::Declaration::Dynamic:0xa737e2c @name=:password, @ignored=false, @block=#<Proc:0xa737760@/home/vijay_demo_project/bank_cucumber/features/support/factories.rb:8>>, #<FactoryGirl::Declaration::Dynamic:0xa29a630 @name=:address, @ignored=false, @block=#<Proc:0x9f761e8@/home/vijay_demo_project/bank_cucumber/features/support/factories.rb:9>>, #<FactoryGirl::Declaration::Dynamic:0xa145b04 @name=:mobile, @ignored=false, @block=#<Proc:0xa754d74@/home/vijay_demo_project/bank_cucumber/features/support/factories.rb:10>>, #<FactoryGirl::Declaration::Dynamic:0xa5d4918 @name=:country, @ignored=false, @block=#<Proc:0xa5d4878@/home/vijay_demo_project/bank_cucumber/features/support/factories.rb:11>>, #<FactoryGirl::Declaration::Dynamic:0xa5d4b5c @name=:login, @ignored=false, @block=#<Proc:0xa5d4ae4@/home/vijay_demo_project/bank_cucumber/features/support/factories.rb:12>>], @name=:user, @overridable=false>, @callbacks=[], @defined_traits=[], @to_create=nil, @base_traits=[], @additional_traits=[], @constructor=nil, @attributes=nil, @compiled=false>, @compiled=false>}>

但是当我创建构建时出现错误。

 FactoryGirl.build(:user)
*** NameError Exception: uninitialized constant User

Rails 有一个模型用户并在数据库中显示表用户。

请帮助我哪里错了。

4

1 回答 1

2

在您调用FactoryGirl.build(:user)时,User模型(在 中定义user.rb)尚未加载到内存中。require 'app/models/user.rb'在调用之前尝试使用FactoryGirl.build(:user).

于 2013-05-28T12:46:19.823 回答