Skip to content
This repository has been archived by the owner on Mar 15, 2021. It is now read-only.

model relationships association with default fabricator #64

Closed
knwang opened this issue Sep 19, 2011 · 4 comments
Closed

model relationships association with default fabricator #64

knwang opened this issue Sep 19, 2011 · 4 comments

Comments

@knwang
Copy link

knwang commented Sep 19, 2011

with ActiveRecord, suppose I have a Book model and an Author model and

class Book < ActiveRecord::Base
has_many :authors, through: :books_authors
end

class Author < ActiveRecord::Base
has_many :books, through: :books_authors
end

And the requirement is that a book has to have at least an author, therefore in my book fabricator, I have

Fabricator(:book) do
authors! { Fabricate(:author) }
end

In my cucumber test, I want to be able to say

Given 1 book
And that book has the following author:
| name | John Doe |
.....

Currently if I do this the book will have two authors, one created with the book fabricator and John Doe. I'd like to be able to only have John Doe has the author for the book.

@paulelliott
Copy link
Owner

You should be doing this the other way around. Always build from the top down.

Given the following author:
| name | John Doe |
And that author has 1 book

@knwang
Copy link
Author

knwang commented Oct 10, 2011

I don't think authors are "on top of" books in this example - they "have many through" each other. But agree with you that coming from the other direction would solve this problem.

@paulelliott
Copy link
Owner

Oh, you are absolutely right. Sorry about that.

The base fabricator should never build things that aren't necessary to persist the object. You should make a :book_with_author fabricator for when you need them together. This will reduce the "magic" in your test suite and make cucumber work a lot better.

@knwang
Copy link
Author

knwang commented Oct 10, 2011

Makes a lot of sense. Thanks!

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

No branches or pull requests

2 participants