FactoryGirl: Factory not registered

CitizenX picture CitizenX · Oct 10, 2013 · Viewed 14.6k times · Source

I work on a project with a structure like:

projects/warehouse/core
projects/warehouse/products/bottles
projects/warehouse/products/boxes

In this project, the application logic, gems, etc. are all in the core application. I have boxes set up for rspec like such:

projects/warehouse/products/boxes/spec
    /factories
    /models

The factories directory contains cubics.rb:

FactoryGirl.define do
  factory :cubic
    id 1
    dimension 12
  end
end

The models directory contains cubic_spec.rb:

require 'spec_helper'

describe Boxes::Cubic do
  it "has a valid factory" do
    FactoryGirl.create(:cubic).should be_valid
  end
end

The Cubic model is located in products/boxes/app/models/boxes/cubic.rb.

module Boxes
  class Cubic < BoxExBase
    self.table_name = 'containers'
    #validation stuff goes here
  end
end

Simple and straightforward. When I execute rspec ../products/boxes/spec/models/cubic_spec.rb I get the ArgumentError: Factory not registered: cubic. I've tried requiring factory_girl_rails in the spec_helper.rb. I've tried modifying the spec_helper.rb w/

FactoryGirl.definition_file_paths << File.join(File.dirname(__FILE__), 'factories')
FactoryGirl.find_definitions

The gemfile in the core contains gem 'factory_girl_rails' in the development, test groups. I've even tried getting the factory to raise an error, but that doesn't even happen. Therefore, the factory doesn't appear to even be getting loaded. What do I need to do to get this factory loaded and registered?

Answer

Ashley Raiteri picture Ashley Raiteri · Jan 23, 2014

You need to help the dummy app (or the rails console) out, since FactoryGirl is going to look in Rails.root, which is spec/dummy.

So, from a console launched in spec/dummy for example just do this:

FactoryGirl.definition_file_paths = %w(../factories)
FactoryGirl.find_definitions
# You can use this line to see what factories are loaded
# FactoryGirl.factories

For your particular case, you'll need to change the actual locations, but where you are, if FactoryGirl isn't finding your factories, it's because it doesn't know where to look.

To be specific: Here is what I did. My needs were as follows - I needed to run rspec from the Gem root directory. But I also need to be able to run the rails console from the embedded dummy project and access Factory girl for convenient test object creation during development.

TLDR