Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fabrication gem cyclic dependency

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?

like image 394
asiniy Avatar asked Jun 06 '26 15:06

asiniy


1 Answers

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.

like image 151
Paul Elliott Avatar answered Jun 08 '26 04:06

Paul Elliott



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!