From 6ea3d555f37b14686d93577261d9e55854f52128 Mon Sep 17 00:00:00 2001 From: John Pitchko Date: Fri, 28 Jun 2024 09:24:01 -0600 Subject: [PATCH] Update docs to require full namespace 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. --- GETTING_STARTED.md | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/GETTING_STARTED.md b/GETTING_STARTED.md index 09590397..dd6ee9b2 100644 --- a/GETTING_STARTED.md +++ b/GETTING_STARTED.md @@ -219,6 +219,26 @@ It is also possible to explicitly specify the class: factory :admin, class: "User" ``` +Explicit specification of the class, _with the full namespace_, is necessary when defining factories for classes within modules in non-Rails applications: + +``` +# foo/bar.rb +module Foo + class Bar + ... + end +end + +# factories.rb +FactoryBot.define do + factory :bar, class: 'Foo::Bar' do + ... + end +end +``` + +If the full namespace is not provided in the `factory` statement, you will receive a `NameError: uninitialized constant Bar` error. + You can pass a constant as well, if the constant is available (note that this can cause test performance problems in large Rails applications, since referring to the constant will cause it to be eagerly loaded).