thoughtbot / factory_bot

A library for setting up Ruby objects as test data.

Home Page:https://thoughtbot.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Problem with attributes using `_id` suffix.

stephannv opened this issue · comments

Description

I have a field to represent payment gateway and payment gateway id (like an external id), but when I use a factory to create or build an object assigning some values to these attributes, FactoryBot cannot build it correctly.

Reproduction Steps

require 'bundler/inline'

gemfile(true) do
  source "https://rubygems.org"
  git_source(:github) { |repo| "https://github.com/#{repo}.git" }

  gem 'activerecord'
  gem 'sqlite3'
  gem 'factory_bot_rails', '6.2.0'
end

require 'active_record'
require 'minitest/autorun'
require 'logger'
require 'factory_bot'

ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: ':memory:')
ActiveRecord::Base.logger = Logger.new(STDOUT)

ActiveRecord::Schema.define do
  create_table :payments do |t|
    t.integer :amount_cents, null: false
    t.string :gateway, null: false
    t.string :gateway_id
  end
end

class Payment < ActiveRecord::Base
end

FactoryBot.define do
  factory :payment do
    amount_cents { 1000 }
    gateway { 'stripe' }
    gateway_id { 'xyz' }
  end
end

class Test < Minitest::Test
  def test_factory
    payment_a = FactoryBot.build(:payment)
    assert_equal payment_a.gateway, 'stripe'
    assert_equal payment_a.gateway_id, 'xyz'

    payment_b = FactoryBot.build(:payment, gateway: 'braintree', gateway_id: 'abc')
    assert_equal payment_b.gateway, 'braintree' # fails because gateway is nil
    assert_equal payment_b.gateway_id, 'abc' # fails because gateway_id is nil
  end
end

Expected behavior

payment_b should have gateway and gateway_id filled with given attributes.

Actual behavior

FactoryBot cannot fill gateway and gateway_id attributes values.

System configuration

factory_bot_rails 6.2.0:
factory_bot 6.2.0:
rails 6.1.4:
ruby 3.0.1:

Maybe this issue should be moved to factory_bot repo 🤔.

I realized this is not a bug. It is working as planned here:

it "for an attribute should include the original attribute and a version suffixed with '_id'" do

Is it possible to disable this behavior for specific attributes?

See #1142 for past discussion

Thanks @composerinteralia. I'm closing this issue to avoid duplicated.