thoughtbot / factory_bot

A library for setting up Ruby objects as test data.
https://thoughtbot.com
MIT License
7.89k stars 2.6k forks source link

Expose which keys were overridden by the user #1649

Open mike-burns opened 2 months ago

mike-burns commented 2 months ago

The context, as passed to the various hooks, does not tell us whether a key was overridden by the user when building/creating/stubbing the object. This means we can't know whether a value is the default, or intentionally set.

Let's expose this on the context. It could be as simple as a list of keys set by the user.

Zooip commented 1 month ago

The list of keys is already exposed in the evaluator using the private undocumented method __override_names__ : https://github.com/thoughtbot/factory_bot/blob/main/lib/factory_bot/evaluator.rb#L50-L52 It would make sense to me to make this method part of the public stable API.

I personnaly use it to "sync" associations' associations like so :

transient do
  school do
    if __override_names__.include?(:exam)
      exam.school
    elsif __override_names__.include?(:student)
      student.school
    else
      association :school
    end
  end
end

exam { association :exam, school: school }
student { association :student, school: school }

So you technically already can use this in the callbacks but it is undocumented and not part of the public API

after(:build) do |instance, evaluator|
  evaluator.__override_names_
end