factory_bot icon indicating copy to clipboard operation
factory_bot copied to clipboard

Testing non-Rails apps with modules requires factories to define fully namespaced classes

Open johnpitchko opened this issue 3 years ago • 2 comments

Description

FactoryBot throws an error when defining factories that refer to classes within modules in non-Rails applications. FactoryBot will work, but the class used by the factory must be explicitly stated in the full namespace. Simply updating the GETTING_STARTED.md document should be sufficient.

Reproduction Steps

# bar.rb
module Foo
  class Bar
    ...
  end
end

# factories.rb
FactoryBot.define do
   factory :bar do
    ...
  end
end

Produces this error: NameError: uninitialized constant Bar

Working Code

# bar.rb
module Foo
  class Bar
    ...
  end
end

# factories.rb
FactoryBot.define do
   factory :bar, class: 'Foo::Bar' do
    ...
  end
end

I'm happy to update GETTING_STARTED.md to explain better and help rookies like me who might get stumped.

johnpitchko avatar Jan 11 '21 04:01 johnpitchko

Sure, I'm all for adding a relevant example to the documentation, maybe somewhere around https://github.com/thoughtbot/factory_bot/blob/master/GETTING_STARTED.md#specifying-the-class-explicitly

composerinteralia avatar Feb 20 '21 03:02 composerinteralia