FactoryGirl factory for a class with names

Any links to documentation that confirm or disprove my thoughts here will be greatly appreciated; I can't seem to find.

AFAIK, if you have a Rails application with a Product model, you can define FactoryGirl factory as

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

and then call factory in tests using (RSpec example)

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

but you can also call it with

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

This is useful if you want your model tests to be more dynamic and not change with the RSpec described_class helper.

My problem:

I have a model that seems to be in the namespace

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

with factory

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

and when trying to use RSpec helpers ...

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

FactoryGirl complains about the missing factory

 Factory not registered: Namespace::MyModel 

Did I miss this FactoryGirl function without understanding its true purpose? Or is there another way I can correctly define my factory?

+7
ruby ruby-on-rails rspec factory-bot
source share
1 answer

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 the name factory, but not the name of the class that defines.

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

Or you can dynamically get the name factory, from the name of the described_class. He has already answered How do you find the namespace / module name programmatically in Ruby on Rails?

+1
source share

All Articles