thoughtbot / thoughtbot/factory_bot

Support for default attributes for JSON columns

Open
#1,525 1 comment 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

feature
Dominant language
Ruby
Stars
8.2k
Forks
2.6k
PR merge metrics
No merged PRs in 30d

Description

Problem this feature will solve

Currently, I can create a factory like this:

FactoryBot.define do
  factory :a do
    my_json_column do
      {
        "a" => 1,
        "b" => 2,
        "c" => 3,
      }
    end
  end
end

and use it like this:

create :a, my_json_column: { "a" => 2, "b" => 3, "c" => 4 }

which means I have to specify every key which I want to appear in my_json_column.

Desired solution

I'm wondering if it would be possible to do something like this:

FactoryBot.define do
  factory :a do
    json :my_json_column do # or maybe hash? or json_factory?
      {
        "a" => 1,
        "b" => 2,
        "c" => 3,
      }
    end
  end
end

which would mean that I could only pass in the properties I cared about, and the rest would just be populated from the definition in the factory (similar to regular properties in factory).

a = create :a, my_json_column: { "a" => 2 }
a.my_json_column # { "a" => 2, "b" => 2, "c" => 3 }

Alternatives considered

I've considered doing something like this (or similar) as a workaround, though it doesn't seem that clean, especially if you are doing it a fair bit.

atrs = attributes_for :a
create :a, my_json_column: { **atrs.my_json_column, "a" => 2 }

But if anyone has any other suggestions then I'm all ears!

Additional context

Example use case:

Imagine you have a config json column, which just stores some flexible key-value pairs for a model; if you have some sort of validation on this, which checks for various keys, it would be cumbersome to specify all of them every time you have a test which just tests a single one of those keys.

Thanks!

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reading the factory definition and the create and attributes_for entry points described in the issue. Check how JSON-column values are currently assigned, then define and test an API for defaults. Done means callers can override selected keys while unspecified keys retain the factory defaults.

Written by the indexing model from the issue text.

Assessment

Tech stack
ruby
Domain
testing
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.