Fabrication gem cyclic dependency

221 views Asked by At

I've got a cyclic dependency when worked with fabrication gem. Here I'll show you what I've did. Let's suppose I have 2 models:

class User < AR::Base
  has_many :messages


class Message < AR::Base
  belongs_to :user

So, the fabricators for them will be:

Fabricator(:user) do
  # bla-bla-bla
  messages(count: 5)
end

Fabricator(:message) do
  # bla-bla-bla
  user
end

It seems all right, yeah? But when I run Fabricate(:user) or Fabricate(:message) I get cyclic dependencies, because of fabricating of message fabricates new user, fabricating new user fabricates a messages for him and so on. How can I avoid this diabolic circle?

1

There are 1 answers

1
Paul Elliott On BEST ANSWER

I would typically have two user fabricators in an instance like this.

Fabricator(:user)

Fabricator(:user_with_messages, from: :user) do
  messages(count: 5)
end

You could alternatively do this to make what you have work.

Fabricator(:user) do
  messages(count: 5) { Fabricate.build(:message, user: nil) }
end

The messages will be saved automatically by AR when the user is saved. It will handle setting up the correct references.