thoughtbot / factory_bot

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

Problem with attributes using `_id` suffix. #1512

Closed stephannv closed 3 years ago

stephannv commented 3 years ago

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:

stephannv commented 3 years ago

Maybe this issue should be moved to factory_bot repo 🤔.

stephannv commented 3 years ago

I realized this is not a bug. It is working as planned here: https://github.com/thoughtbot/factory_bot/blob/92114db048b70096183af622173506535b150e65/spec/factory_bot/aliases_spec.rb#L2

Is it possible to disable this behavior for specific attributes?

composerinteralia commented 3 years ago

See https://github.com/thoughtbot/factory_bot/issues/1142 for past discussion

stephannv commented 3 years ago

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