thoughtbot / factory_bot

A library for setting up Ruby objects as test data.
https://thoughtbot.com
MIT License
7.9k stars 2.6k forks source link

Writing a factory for a method that belongs_to two different instance of the same model and requires its id's #1168

Closed denisse-dev closed 6 years ago

denisse-dev commented 6 years ago

I have a User model that has_many accounts, each Account belongs_to one user and has_many transactions, each Transactions to two different accounts (sender_account and recipient_account), the original belongs_to method that adds the factory (like account) will not work since I need a sender_account and recipient_account.

If I manually set the ID with sender_account 1 and run rpsec I get:

ActiveRecord::AssociationTypeMismatch:
       Account(#5570447856500) expected, got 1 which is an instance of Integer(#5570414320800)

Even when the ID's are stored as Integer.

How can I add an association when my model belongs_to to different instances of the same model? I already have my Account and User factory defined and they work as expected.

denisse-dev commented 6 years ago

Thanks to thelp of Igor Drozdov I was able to figure out what was wrong (in case someone gets to this Issue with the same problem).

I defined my associations with: association :sender_account, factory: :account, strategy: :build association :recipient_account, factory: :account, strategy: :build

When the strategy was not needed as it didn't save the accounts and therefore the tests were failing.