As I was working on the Rails tutorial with rspec support, I was addicted to creating Relationship test data for the user in Listing 14.28 in 14.2.3 with FactoryBot, so I'll post it as a reminder.
(1) Define the fixture that creates the relationship test data in FactoryBot as shown below. (2) Create user test data in the FactoryBot definition at the same time.
ruby:test/fixtures/relationships.yml(Listing 14.28)
one:
follower: michael
followed: lana
two:
follower: michael
followed: malory
three:
follower: lana
followed: michael
four:
follower: archer
followed: michael
Give it a try and list the solutions you have adopted.
This is the most straightforward method. Create a factory for the Relationship class with follower_id and followed_id. However, I couldn't set the association well by this method, so I created the user test data separately.
spec/factories/relationships.rb
factory :relationship, class: Relationship do
follower_id { follower.id }
followed_id { followed.id }
end
spec/models/relationship_spec.rb
RSpec.describe Relationship, type: :model do
let(:follower) { create(:user) }
let(:followed) { create(:user) }
let(:relationship) { create(:relationship, follower: follower, followed: followed) }
it { expect(relationship).to be_valid }
end
The second method is to create test data for users with relationships. The user's test data does not need to have a relationship in every test, so we allow it to be set as needed in the trait. This way, you don't have to create user and relationship test data respectively. However, this method is just a method of creating test data of user, and it seems that it is not suitable for testing relationship because it is necessary to pass user to call relationship.
spec/factories/users.rb
factory :user do
.
.
.
trait :has_followed do
after(:create) do |user|
followed = create(:user)
user.follow(followed)
end
end
end
spec/models/relationship_spec.rb
RSpec.describe Relationship, type: :model do
let(:user) { create(:user, :has_followed) }
it { expect(user.actve_relationships).to be_valid }
end
In the end, I couldn't find a solution to completely achieve ①②, so I decided to write the relationship test in part 1 and the relationship user test in part 2.
-FactoryBot (FactoryGirl) Cheat Sheet -Create has_many through association with factory_bot -Only 5 things to remember when using FactoryBot
Recommended Posts