FactoryGirl factory for namespaced class
Asked Answered
M

1

12

Any links to documentation proving or disproving my thoughts here would be very appreciated; I can't seem to find any.

AFAIK, if you had a Rails application with a Product model, you could define a FactoryGirl factory as

FactoryGirl.define do
  factory :product do
    # stuffs
  end
end

and then call your factory in tests with (RSpec example)

let(:product) { FactoryGirl.create(:product) }

but you may also call it with

let(:product) { FactoryGirl.create(Product) }

This is helpful if you're wanting to keep your model tests a bit more dynamic and free to change with RSpec's described_class helper.

My problem:

I've got a model that happens to be namespaced

class Namespace::MyModel < ActiveRecord::Base
  # model stuffs
end

with a factory

FactoryGirl.define do
  factory :my_model, class: Namespace::MyModel do
    # factory stuffs
  end
end

and when attempting to use RSpec's helpers...

RSpec.describe Namespace::MyModel do
  let(:my_object) { FactoryGirl.create(described_class) }
  # testing stuffs
end

FactoryGirl complains of a missing factory

Factory not registered: Namespace::MyModel

Am I missing this feature of FactoryGirl, without understanding its true purpose? Or is there another way I can define my factory to resolve correctly?

Melodist answered 29/1, 2015 at 19:48 Comment(3)
possible duplicate of Using factory_girl_rails with Rspec on namespaced modelsAnatolic
@GregBurghardt I know how to set up the factory and use it as documented by FactoryGirl. My question pertains to how FactoryGirl resolves classnames to factory names.Melodist
For anyone who may be curious, I've also opened up an issue on FactoryGirl's GitHub page to try and get the opinions of the development team on this: github.com/thoughtbot/factory_girl/issues/740Melodist
C
2

Why don't you try

RSpec.describe Namespace::MyModel do
  let(:my_object) { FactoryGirl.create(:my_factory) }
  # testing stuffs
end

FactoryGirl is usually used by factory name, but not class name, that is defines.

You can have a multiple factories, that define instances of the same class. The difference between them can be in fields values, for example.

Or you can dynamicly get factory name, from described_class name. It is already answered at How do you find the namespace/module name programmatically in Ruby on Rails?

Cyndy answered 29/1, 2015 at 20:6 Comment(1)
You're absolutely right. Using the factory as you describes works fine. I've been doing that. What I'm curious of is whether I can pass a namespaced class name to FactoryGirl and have it resolve to a factory that is defined on that class.Melodist

© 2022 - 2024 — McMap. All rights reserved.