ruby-on-rails – FactoryGirl在开发环境中创建对象

当我在开发中启动rails控制台时,我看到FactoryGirl创建了对象.显然我做错了,但是这样做的正确方法是什么?这段代码使我的测试工作……

# tests/factories/board.rb
FactoryGirl.define do

    factory :word do
        sequence(:text) { |n| "FAKETEXT#{n}" }
    end

    factory :board do
        trait :has_words do
            words [
                FactoryGirl.create(:word,id: "514b81cae14cfa78f335e250"),FactoryGirl.create(:word,id: "514b81cae14cfa7917e443f0"),id: "514b81cae14cfa79182407a2"),id: "514b81cae14cfa78f581c534")
            ]
        end
    end

end

请注意,在我的配置目录中的任何文件中都没有提到工厂的任何内容,因此gem会自动进行任何加载.我的Gemfile的相关部分是:

# Stuff not to use in production
group :development,:test do
    # Command-line debugger for development
    gem "debugger"

    # for unit testing - replace fixtures
    gem "factory_girl_rails"
end

所以我可以把工厂女孩带出开发环境.但我认为这些记录是在工厂使用之前创建的,这表明我的工厂编写错误.但如果你告诉我工厂写得正确,我就会这样做.

解决方法

有同样的问题.有两种方法可以解决这个问题,

1.使用FactoryGirl语法引用工厂中的Factory.

用factory :: my_factory替换FacotryGirl.create(:my_factory)

关于此的更多信息,https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md#associations

2. factory_girl:require =>在Gemfile中为false

这会导致Factories在启动时生成对象,

group :development,:test do  
  gem 'factory_girl_rails'
end

为什么?在Rails启动期间,Bundler需要开发组中的所有gem,而FactoryGirl似乎需要所有工厂文件.要求工厂评估Ruby代码,因此调用FactoryGirl.create(:my_factory).

这可以修复,

# Gemfile
group :development,:test do  
  gem 'factory_girl_rails',:require => false
end

只需确保在测试环境中手动要求factory_girl,EG

# spec_helper
require 'factory_girl'

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...