DEV Community

n350071๐Ÿ‡ฏ๐Ÿ‡ต
n350071๐Ÿ‡ฏ๐Ÿ‡ต

Posted on โ€ข Edited on

17 8

[RSpec] Factorybot transient & trait with argument

๐Ÿค” 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


Enter fullscreen mode Exit fullscreen mode

๐Ÿ‘ 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


Enter fullscreen mode Exit fullscreen mode


let!(:user) { create(:user, :with_book, title: 'Ruby') }


Enter fullscreen mode Exit fullscreen mode

๐Ÿ”— Parent Note

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (2)

Collapse
 
samuelfaure profile image
Samuel-Zacharie FAURE โ€ข

Thank you for this small snippet, it was quite useful!

Collapse
 
mxdavis profile image
Malki Davis โ€ข

Very helpful! Small thing -- there should be a do after trait :with_book

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free โ†’

๐Ÿ‘‹ Kindness is contagious

Please leave a โค๏ธ or a friendly comment on this post if you found it helpful!

Okay