[RSpec] Factorybot transient & trait with argument
n350071π―π΅
Posted on November 7, 2019
π€ Situation
You want to make a user with a book that title is 'Ruby'.
class User
has_many: books
end
class Book
belongs_to: user
end
π Solution
- trait: you can run the process
- trait with arguments: It is DEPRECATED, we should use
transient
instead. - transient: you can define and pass arguments with the block
FactoryBot.define do
factory :user, class: User do
trait :with_book
transient do
# π¦1. default value when you use :with_book trait
# π¦2. Dont't assign just 'Agile'. see also: https://thoughtbot.com/blog/deprecating-static-attributes-in-factory_bot-4-11
title { 'Agile' }
end
after(:build) do |user, evaluator|
user.book = FactoryBot.create(:book, title: evaluator.title)
end
end
end
factory :book, class Book do
sequence(:title) { |n| "book no.#{n}" } # π¦ default value
end
end
let!(:user) { create(:user, :with_book, title: 'Ruby') }
π Parent Note
π πͺ π
π©
n350071π―π΅
Posted on November 7, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.