Using FactoryBot with a PORO

You can, and probably should, do that.

Cody Brooks
By Cody Brooks
October 11, 2023

Psst… You can use FactoryBot to test Plain ole Ruby Objects.

So go ahead.
Extract a PORO.
Write a spec.
Guaranteed to give you that ‘I made my bed today’ kind of feeling.

# app/models/arrow_down.rb
class ArrowDown
  # Build an arrow beginning at @from and ending at @to
  # from |-╮ |
  #      | |  |
  #   to |<╯ |

  attr_reader :from, :to

  def initialize :from, :to
    @from = from
    @to = to

  # Really cool, well written, arrow methods
# spec/factories/arrow_down_factory.rb
FactoryBot.define do
  factory :arrow_down, class: ArrowDown do
    from  { 0 }
    to    { 2 }

    initialize_with { new( from: from, to: to ) }
# spec/models/arrow_down_spec.rb
require "rails_helper"

RSpec.describe ArrowDown, type: :model do
  let(:arrow_down) { }

  it "should point down" do
    expect(arrow_down.direction).to eq(:down)
  # Really cool, well written, tests

Want more? Allow me to point you in the direction of a great blog Tips for Using FactoryBot Without an ORM.

If you’re looking for a team to help you discover the right thing to build and help you build it, get in touch.