I want to create a convenient method in rspec that creates a set of factorybot and make it common among files.

Asked 2 years ago, Updated 2 years ago, 75 views

You want to create a set of 3 users and their associated data as follows:

before do
  user1 = create(:user)
  create(:profile, user_id:user1.id)
  create(:image,user_id:user1.id)
  create(:birthday,user_id:user1.id)

  user2=create(:user)
  create(:profile, user_id:user2.id)
  create(:image,user_id:user2.id)
  create(:birthday,user_id:user2.id)

  user3=create(:user)
  create(:profile, user_id:user3.id)
  create(:image,user_id:user3.id)
  create(:birthday,user_id:user3.id)

  create(:article, user_id:user1.id)
  create(:article, user_id:user2.id)
  create(:article, user_id:user3.id)
end

The above is redundant, so I would like to do the following.

def create_user
  user=create(:user)
  create(:profile, user_id:user.id)
  create(:image,user_id:user.id)
  create(:birthday,user_id:user.id)
end

before do
  user1 = create_user
  user2 = create_user
  user3 = create_user

  create(:article, user_id:user1.id)
  create(:article, user_id:user2.id)
  create(:article, user_id:user3.id)
end

I wanted to make this create_user method common to other file specs.
It seems that rspec writes common processing in the directory supports, but can I use concerns which is often used in models to make it common?

ruby-on-rails rspec

2022-09-30 16:48

1 Answers

First, you can write the following to create the relevant records at the same time:

 create(:user) do | user|
  create(:profile, user_id:user.id)
  create(:image,user_id:user.id)
  create(:birthday,user_id:user.id)
end

Alternatively, if these associations are absolutely necessary, they can be created only by create(:user) defining them in the user factory from the beginning.If it is optional but often used, defining it as trit will reduce the amount of code.

Next, if you use the user factory to create more than one mock, you can write create_list.

create_list(:user,3)

If you define the association on the factory side, you only need the code above, and if you decide to use the block, create_list will accept the block, so you can write it in a similar way.

I think using these techniques will reduce the amount of code without having to define a method.

Factorybot's useful features are well organized in GETTING_STARTED, so it's convenient to read them. https://github.com/thoughtbot/factory_bot/blob/master/GETTING_STARTED.md


2022-09-30 16:48

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.