Pass parameter in setting attribute on association in FactoryGirl

The association helper in factory_girl can’t take dynamic property arguments, but you can use a dynamic attribute to instantiate the association however you want:

factory :tx_link do
  units "9.99"

  factory :link_red_to_sub do
    transient do
      sub 0
      red 0
    end
    units { red }

    giver { create(:transaction, units: sub) }
    taker { create(:redemption, units: red) }
  end
end

The only downside of this is that the giver and taker associations will use the create strategy regardless of what strategy you’re building tx_link with, which essentially means that attributes_for and build_stubbed won’t work correctly for the tx_link factory.

The example I provided requires version 4.5.0.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)