Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How do you do inline association attribute overrides when your association doesnt match the factory name? #1591

Open
v2kovac opened this issue Aug 30, 2023 · 2 comments

Comments

@v2kovac
Copy link

v2kovac commented Aug 30, 2023

The docs here use the worst example where the association happens to match the factory:
https://github.com/thoughtbot/factory_bot/blob/main/GETTING_STARTED.md#overriding-attributes

factory :post do
  # ...
  author_last_name { "Writely" }
  author { association :author, last_name: author_last_name }
end

What if "author" is called "previous_author" on the model, I've tried every variation of explicitly specify the factory and it doesn't work.

eg: previous_author factory: :author { ... } doesn't work, previous_author { ... factory: :author } doesn't work etc. Is this just not possible?

@v2kovac
Copy link
Author

v2kovac commented Aug 30, 2023

author { association :previous_author, factory: :author }, doesn't work either btw because it says "previous_author" key not found lol, not to mention if you have more than one author (previous_author and new_author) you cant have author and author specified twice.

@ellnix
Copy link

ellnix commented Oct 1, 2023

I am assuming from your comments that your models have this structure:

class Author < ApplicationRecord
end
class Post < ApplicationRecord
  belongs_to :previous_author, class_name: 'Author' # ...
end

In that case I believe

factory :post do
   author_last_name { "Writely" }
   previous_author { association :author, last_name: author_last_name }
end

ought to work.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants