Today I Learned

hashrocket A Hashrocket project

Use foreign-key like attributes with FactoryBot

An odd issue occurs when trying to use attributes similar to methods you'd expect with Rails ActiveRecord relationships in FactoryBot.

Take a relationship named provider. You would expect the ActiveRecord object to have methods for provider and provider_id.

However, some interesting behavior happens when you legitimately have a reason to have methods with those names, not during an ActiveRecord relationship.

FactoryBot.define do
  factory :widget do
    url { "URL" }
    provider { "PROVIDER_NAME" }
    provider_id { "PROVIDER_ID" }
  end
end

One will get cleared out when providing the attributes for provider and provider_id.

There is a long-running issue regarding this, but for now, this is how I could remedy the situation. Set the methods as transient attributes and merge the attributes during initialization.

FactoryBot.define do
  factory :widget do
    url { "URL" }

    transient do
      provider { "PROVIDER" }
      provider_id { "PROVIDER_ID" }
    end

    initialize_with do
      new(
        attributes.merge(
          provider: provider,
          provider_id: provider_id
        )
      )
    end
  end
end
See More #rails TILs
Looking for help? Hashrocket has been an industry leader in Ruby on Rails since 2008. Rails is a core skill for each developer at Hashrocket, and we'd love to take a look at your project. Contact us and find out how we can help you.