Ruby factory bot
From wikinotes
Library for creating test data in ruby.
NOTE:
There is also ruby factory_bot_rails.
Documentation
official docs (book) https://thoughtbot.github.io/factory_bot/ official docs https://github.com/thoughtbot/factory_bot/wiki quickstart docs https://github.com/thoughtbot/factory_bot/blob/master/GETTING_STARTED.md github https://github.com/thoughtbot/factory_bot
Tutorials
factorybot without orm https://thoughtbot.com/blog/tips-for-using-factory-girl-without-an-orm
Basics
FactoryBot.define do factory :user do # <-- User class first_name { "John" } # <-- value between brackets last_name { "Doe" } stats = { {"a" => nil, "b" => nil} } # <-- double quotes for hash admin { false } end enduser = build(:user) # instantiates User user = create(:user) # instantiates User, calls #save() method users = create_list(:user, 10) # create 10x users stub = build_stubbed(:user) # creates stub (all attributes/methods, and associations are faked) attrs = attributes_for(:user) # creates hash to instantiate User instance # can be used in 'do' block create(:user) do |user| user.posts.create(attributes_for(:post)) end
Associations
factory :post do association :author # assigned factory :author association :author, factory: :user # assigned to `author`, but uses facotry `:user` end
Traits
Traits are implemented as constructor arguments.
They are presets of object-attribute values.FactoryBot.define do factory :user do first_name = "Alex" last_name = "Guthrie" languages = ["English"] trait :bilingual do languages = ["English", "French"] end end endFactoryBot.create(:user, :bilingual) # <- creates a bilingual user
Stubbing Methods
FactoryBot is designed not to alter your object. This is ugly, but effective.
FactoryBot.define do factory :user do after(:build) do |user, _evaluator| user.define_singleton_method(:fetch_age) { 30 } end end end