Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FactoryGirl factory for namespaced class

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?

like image 617
Brad Rice Avatar asked Jan 29 '15 19:01

Brad Rice


1 Answers

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?

like image 155
Stanislav Mekhonoshin Avatar answered Oct 17 '22 15:10

Stanislav Mekhonoshin