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?
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
853 When building Fast API+Uvicorn environment with PyInstaller, console=False results in an error
583 Uncaught (inpromise) Error on Electron: An object could not be cloned
589 GDB gets version error when attempting to debug with the Presense SDK (IDE)
563 rails db:create error: Could not find mysql2-0.5.4 in any of the sources
© 2024 OneMinuteCode. All rights reserved.