How to create FactoryBot factory for model that has validation on minimum amount of associated records?FactoryBot - create nested objectsFind or create record through factory_girl associationValidation error on associated factory when using FactoryGirl with RSpecFactories for Models with AssociationsFactory Girl - How to create a factory for a model that has associations?factory girl rails traits for model associationsValidating That A has_many Association Has At Least One Model When Using FactoryGirlHow do I associate a single record with a multiple factory girl models?How to create an associated record within factory girl to pass validations at creationRails Factory Girl: Create record associated with user but with roleFactory Bot associations with namespaced model glitching

What are these white rings in the Undead parish?

What stops you from using fixed income in developing countries?

Why did my folder names end up like this, and how can I fix this using a script?

What does it take for witness testimony to be believed?

Why is strlen so complex in C?

Given current technology, could TV display screens double as video camera sensors?

about to retire but not retired yet, employed but not working any more

What's special ammo?

Thought experiment and possible contradiction between electromagnetism and special relativity

I don't have the theoretical background in my PhD topic. I can't justify getting the degree

How were medieval castles built in swamps or marshes without draining them?

Router on a stick not connecting 2 different VLANs

Do you pay one or two mana to bounce a transformed Delver of Secrets with Repeal?

How do you capitalize agile costs with less mature teams?

Why should a self-financing strategy be previsible?

How much does Commander Data weigh?

How many birds in the bush?

Can an Arcane Focus be embedded in one's body?

Retroactively modifying humans for Earth?

Count the number of paths to n

1mth baby boy keeps peeing through diapers, sometimes diper seems practically unused

Half filled water bottle

Make utility using LINQ

How do I remap "å" to type "å"?



How to create FactoryBot factory for model that has validation on minimum amount of associated records?


FactoryBot - create nested objectsFind or create record through factory_girl associationValidation error on associated factory when using FactoryGirl with RSpecFactories for Models with AssociationsFactory Girl - How to create a factory for a model that has associations?factory girl rails traits for model associationsValidating That A has_many Association Has At Least One Model When Using FactoryGirlHow do I associate a single record with a multiple factory girl models?How to create an associated record within factory girl to pass validations at creationRails Factory Girl: Create record associated with user but with roleFactory Bot associations with namespaced model glitching






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















I have a User model that is only valid when there is at least one Address:



class User
has_many :addresses
validates :addresses, length: miniumum: 1
end

class Address
belongs_to :user
end


I tried defining my FactoryBot factory like this:



FactoryBot.define do
factory :user do
association :address
name 'test'
end
end


When creating a user with create(:user), there's an error that user could not be saved due to missing address. It seems the association is only created after the user is created (which obviously creates a validation error). What's the correct way to build my factory?



Thanks










share|improve this question
























  • How does it work in real life? I mean - how can I set a user_id for an address without creating a user?

    – MrShemek
    Mar 27 at 20:33












  • By saving the user and a minimum of 1 address through a nested form, in which user accepts nested attributes for the address. This part is already working, just wanted to write tests for this.

    – bo-oz
    Mar 28 at 5:47











  • Possible duplicate of FactoryBot - create nested objects

    – berkes
    Mar 28 at 8:34

















0















I have a User model that is only valid when there is at least one Address:



class User
has_many :addresses
validates :addresses, length: miniumum: 1
end

class Address
belongs_to :user
end


I tried defining my FactoryBot factory like this:



FactoryBot.define do
factory :user do
association :address
name 'test'
end
end


When creating a user with create(:user), there's an error that user could not be saved due to missing address. It seems the association is only created after the user is created (which obviously creates a validation error). What's the correct way to build my factory?



Thanks










share|improve this question
























  • How does it work in real life? I mean - how can I set a user_id for an address without creating a user?

    – MrShemek
    Mar 27 at 20:33












  • By saving the user and a minimum of 1 address through a nested form, in which user accepts nested attributes for the address. This part is already working, just wanted to write tests for this.

    – bo-oz
    Mar 28 at 5:47











  • Possible duplicate of FactoryBot - create nested objects

    – berkes
    Mar 28 at 8:34













0












0








0








I have a User model that is only valid when there is at least one Address:



class User
has_many :addresses
validates :addresses, length: miniumum: 1
end

class Address
belongs_to :user
end


I tried defining my FactoryBot factory like this:



FactoryBot.define do
factory :user do
association :address
name 'test'
end
end


When creating a user with create(:user), there's an error that user could not be saved due to missing address. It seems the association is only created after the user is created (which obviously creates a validation error). What's the correct way to build my factory?



Thanks










share|improve this question














I have a User model that is only valid when there is at least one Address:



class User
has_many :addresses
validates :addresses, length: miniumum: 1
end

class Address
belongs_to :user
end


I tried defining my FactoryBot factory like this:



FactoryBot.define do
factory :user do
association :address
name 'test'
end
end


When creating a user with create(:user), there's an error that user could not be saved due to missing address. It seems the association is only created after the user is created (which obviously creates a validation error). What's the correct way to build my factory?



Thanks







ruby-on-rails rspec factory-bot






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 27 at 20:00









bo-ozbo-oz

1,8991 gold badge13 silver badges32 bronze badges




1,8991 gold badge13 silver badges32 bronze badges















  • How does it work in real life? I mean - how can I set a user_id for an address without creating a user?

    – MrShemek
    Mar 27 at 20:33












  • By saving the user and a minimum of 1 address through a nested form, in which user accepts nested attributes for the address. This part is already working, just wanted to write tests for this.

    – bo-oz
    Mar 28 at 5:47











  • Possible duplicate of FactoryBot - create nested objects

    – berkes
    Mar 28 at 8:34

















  • How does it work in real life? I mean - how can I set a user_id for an address without creating a user?

    – MrShemek
    Mar 27 at 20:33












  • By saving the user and a minimum of 1 address through a nested form, in which user accepts nested attributes for the address. This part is already working, just wanted to write tests for this.

    – bo-oz
    Mar 28 at 5:47











  • Possible duplicate of FactoryBot - create nested objects

    – berkes
    Mar 28 at 8:34
















How does it work in real life? I mean - how can I set a user_id for an address without creating a user?

– MrShemek
Mar 27 at 20:33






How does it work in real life? I mean - how can I set a user_id for an address without creating a user?

– MrShemek
Mar 27 at 20:33














By saving the user and a minimum of 1 address through a nested form, in which user accepts nested attributes for the address. This part is already working, just wanted to write tests for this.

– bo-oz
Mar 28 at 5:47





By saving the user and a minimum of 1 address through a nested form, in which user accepts nested attributes for the address. This part is already working, just wanted to write tests for this.

– bo-oz
Mar 28 at 5:47













Possible duplicate of FactoryBot - create nested objects

– berkes
Mar 28 at 8:34





Possible duplicate of FactoryBot - create nested objects

– berkes
Mar 28 at 8:34












2 Answers
2






active

oldest

votes


















0















Try with:



FactoryBot.define do
factory :user do
name 'test'

before(:create) do |user|
user.addresses << build(:address, user: user)
end
end
end


Please remember to create a factory for address as well.






share|improve this answer


































    0















    association attribute, should only be used if the model contains the foreign key (the model which you declared belongs_to on it). Remove association :address from your factory and use before(:create) callback to build addresses before saving user:



    FactoryBot.define do
    factory :user do
    name 'test'
    before(:create) object.addresses.build()
    end
    end





    share|improve this answer



























    • This will still not let me create(:user) without a validation error (you must provide an address)

      – bo-oz
      Mar 28 at 5:48











    • Sorry, it was mistake. See the updated answer.

      – Sajad Rastegar
      Mar 28 at 8:18











    • You also must correct the spelling error in the word minimum in your validates clause.

      – Sajad Rastegar
      Mar 28 at 8:21











    • @SajadRastegar I have checked your solution but it is not working. That's why I decided to post a little bit different answer that works for me.

      – MrShemek
      Mar 28 at 8:27














    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55385537%2fhow-to-create-factorybot-factory-for-model-that-has-validation-on-minimum-amount%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0















    Try with:



    FactoryBot.define do
    factory :user do
    name 'test'

    before(:create) do |user|
    user.addresses << build(:address, user: user)
    end
    end
    end


    Please remember to create a factory for address as well.






    share|improve this answer































      0















      Try with:



      FactoryBot.define do
      factory :user do
      name 'test'

      before(:create) do |user|
      user.addresses << build(:address, user: user)
      end
      end
      end


      Please remember to create a factory for address as well.






      share|improve this answer





























        0














        0










        0









        Try with:



        FactoryBot.define do
        factory :user do
        name 'test'

        before(:create) do |user|
        user.addresses << build(:address, user: user)
        end
        end
        end


        Please remember to create a factory for address as well.






        share|improve this answer















        Try with:



        FactoryBot.define do
        factory :user do
        name 'test'

        before(:create) do |user|
        user.addresses << build(:address, user: user)
        end
        end
        end


        Please remember to create a factory for address as well.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Mar 28 at 8:26

























        answered Mar 27 at 20:04









        MrShemekMrShemek

        1,9991 gold badge11 silver badges14 bronze badges




        1,9991 gold badge11 silver badges14 bronze badges


























            0















            association attribute, should only be used if the model contains the foreign key (the model which you declared belongs_to on it). Remove association :address from your factory and use before(:create) callback to build addresses before saving user:



            FactoryBot.define do
            factory :user do
            name 'test'
            before(:create) object.addresses.build()
            end
            end





            share|improve this answer



























            • This will still not let me create(:user) without a validation error (you must provide an address)

              – bo-oz
              Mar 28 at 5:48











            • Sorry, it was mistake. See the updated answer.

              – Sajad Rastegar
              Mar 28 at 8:18











            • You also must correct the spelling error in the word minimum in your validates clause.

              – Sajad Rastegar
              Mar 28 at 8:21











            • @SajadRastegar I have checked your solution but it is not working. That's why I decided to post a little bit different answer that works for me.

              – MrShemek
              Mar 28 at 8:27
















            0















            association attribute, should only be used if the model contains the foreign key (the model which you declared belongs_to on it). Remove association :address from your factory and use before(:create) callback to build addresses before saving user:



            FactoryBot.define do
            factory :user do
            name 'test'
            before(:create) object.addresses.build()
            end
            end





            share|improve this answer



























            • This will still not let me create(:user) without a validation error (you must provide an address)

              – bo-oz
              Mar 28 at 5:48











            • Sorry, it was mistake. See the updated answer.

              – Sajad Rastegar
              Mar 28 at 8:18











            • You also must correct the spelling error in the word minimum in your validates clause.

              – Sajad Rastegar
              Mar 28 at 8:21











            • @SajadRastegar I have checked your solution but it is not working. That's why I decided to post a little bit different answer that works for me.

              – MrShemek
              Mar 28 at 8:27














            0














            0










            0









            association attribute, should only be used if the model contains the foreign key (the model which you declared belongs_to on it). Remove association :address from your factory and use before(:create) callback to build addresses before saving user:



            FactoryBot.define do
            factory :user do
            name 'test'
            before(:create) object.addresses.build()
            end
            end





            share|improve this answer















            association attribute, should only be used if the model contains the foreign key (the model which you declared belongs_to on it). Remove association :address from your factory and use before(:create) callback to build addresses before saving user:



            FactoryBot.define do
            factory :user do
            name 'test'
            before(:create) object.addresses.build()
            end
            end






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Mar 28 at 8:27

























            answered Mar 27 at 20:58









            Sajad RastegarSajad Rastegar

            9072 gold badges14 silver badges26 bronze badges




            9072 gold badges14 silver badges26 bronze badges















            • This will still not let me create(:user) without a validation error (you must provide an address)

              – bo-oz
              Mar 28 at 5:48











            • Sorry, it was mistake. See the updated answer.

              – Sajad Rastegar
              Mar 28 at 8:18











            • You also must correct the spelling error in the word minimum in your validates clause.

              – Sajad Rastegar
              Mar 28 at 8:21











            • @SajadRastegar I have checked your solution but it is not working. That's why I decided to post a little bit different answer that works for me.

              – MrShemek
              Mar 28 at 8:27


















            • This will still not let me create(:user) without a validation error (you must provide an address)

              – bo-oz
              Mar 28 at 5:48











            • Sorry, it was mistake. See the updated answer.

              – Sajad Rastegar
              Mar 28 at 8:18











            • You also must correct the spelling error in the word minimum in your validates clause.

              – Sajad Rastegar
              Mar 28 at 8:21











            • @SajadRastegar I have checked your solution but it is not working. That's why I decided to post a little bit different answer that works for me.

              – MrShemek
              Mar 28 at 8:27

















            This will still not let me create(:user) without a validation error (you must provide an address)

            – bo-oz
            Mar 28 at 5:48





            This will still not let me create(:user) without a validation error (you must provide an address)

            – bo-oz
            Mar 28 at 5:48













            Sorry, it was mistake. See the updated answer.

            – Sajad Rastegar
            Mar 28 at 8:18





            Sorry, it was mistake. See the updated answer.

            – Sajad Rastegar
            Mar 28 at 8:18













            You also must correct the spelling error in the word minimum in your validates clause.

            – Sajad Rastegar
            Mar 28 at 8:21





            You also must correct the spelling error in the word minimum in your validates clause.

            – Sajad Rastegar
            Mar 28 at 8:21













            @SajadRastegar I have checked your solution but it is not working. That's why I decided to post a little bit different answer that works for me.

            – MrShemek
            Mar 28 at 8:27






            @SajadRastegar I have checked your solution but it is not working. That's why I decided to post a little bit different answer that works for me.

            – MrShemek
            Mar 28 at 8:27


















            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55385537%2fhow-to-create-factorybot-factory-for-model-that-has-validation-on-minimum-amount%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

            SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

            은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현