# FactoryBot

Published articles for FactoryBot.

This is one page of public article previews, not the complete archive. Follow Next page to continue. Summaries are not the original full articles.

## Testing Rails Apps with FactoryBot and MiniTest

DevFeed: [Testing Rails Apps with FactoryBot and MiniTest](<https://devfeed.tech/articles/testing-rails-apps-with-factorybot-and-minitest-28292.md>)

Original publisher: [Read original article](<http://fuzzyblog.io/blog/rails/2022/07/27/testing-rails-apps-with-factorybot-and-minitest.html>)

Author: Fuzzygroup

Published: 2022-07-27T10:58:00Z

Content type: tutorial

Language: en

Sources: [Scott Johnson](<https://devfeed.tech/sources/scott-johnson.md>)

Topics: [Testing](<https://devfeed.tech/topics/testing.md>), [Rails](<https://devfeed.tech/topics/rails.md>), [Code](<https://devfeed.tech/topics/code.md>), [Framework](<https://devfeed.tech/topics/framework.md>), [RSpec](<https://devfeed.tech/topics/rspec.md>)

Tags: [factorybot](<https://devfeed.tech/tags/factorybot.md>), [rails](<https://devfeed.tech/tags/rails.md>), [rspec](<https://devfeed.tech/tags/rspec.md>), [testing](<https://devfeed.tech/tags/testing.md>)

### AI overview

A tutorial on testing Rails applications with FactoryBot and MiniTest. It explains how to define factories, use traits for different scenarios such as pools and hot tubs, and test Rails model methods. The article notes that RSpec is not required for FactoryBot.

### Source excerpt

Pizza courtesy of Pizza for Ukraine! Donate Now to Pizza for Ukraine This blog post looks at testing rails apps with FactoryBot and MiniTest - the default test framework which ships with Rails. It does not use RSpec and RSpec is NOT required for use with FactoryBot. Note: I believe that MiniTest is the name of the standard rails testing framework. Oddly I've had issues confirming that so if I'm wrong please feel free to tell me. Creating a Factory A factory is a pluralized file just as is a fixture. Factories live, generally, in the test/factories/ directory. Let's say that you were modeling swimming pools. You might have this factory: FactoryBot.define do factory :pool do user water_chemistry_type name { "Swimming Pool" } pool_type { "pool"} length {38} width {18} units { "feet"} volume_units {"gallons"} shallow_end_depth { 3} deep_end_depth {7.67} end end What the above code says: Define a factory named :pool Reference two other models - user and water_chemistry_type Have a bunch of attributes that define the pool Creating Two Specific Factories The power of something like FactoryBot comes, however, not when we have a single instance of anything but when we have multiple instances that we can use to test different scenarios. Let's say that I have both a pool and a hot tub. Those have commonalities but also differences. We can model those difference as traits. FactoryBot.define do factory :pool do user water_chemistry_type trait :swimming_pool do name { "Swimming Pool" } pool_type { "pool"} length {38} width {18} units { "feet"} volume_units {"gallons"} shallow_end_depth { 3} deep_end_depth {7.67} end trait :hot_tub do name {"Hot Tub"} pool_type {"hot_tub"} length { 6 } width { 6 } units { "feet"} volume_units { "gallons" } depth { 3 } end end end What this does is: Create a pool factory With two common attributes - user and water_chemistry_type Add a trait named "swimming" pool which defines the attributes for a swimming pool. Add a trait named "hot_tub" which def

## Rails Tip : When You Are Testing Model Files without a Database Table Delete Fixtures File

DevFeed: [Rails Tip : When You Are Testing Model Files without a Database Table Delete Fixtures File](<https://devfeed.tech/articles/rails-tip-when-you-are-testing-model-files-without-a-database-table-delete-fixtures-file-28291.md>)

Original publisher: [Read original article](<http://fuzzyblog.io/blog/rails/2022/07/20/rails-tip-when-you-are-testing-model-files-without-a-database-table-delete-fixtures-file.html>)

Author: Fuzzygroup

Published: 2022-07-20T14:02:00Z

Content type: tutorial

Language: en

Sources: [Scott Johnson](<https://devfeed.tech/sources/scott-johnson.md>)

Topics: [Rails](<https://devfeed.tech/topics/rails.md>), [Testing](<https://devfeed.tech/topics/testing.md>), [Ruby](<https://devfeed.tech/topics/ruby.md>)

Tags: [activerecord](<https://devfeed.tech/tags/activerecord.md>), [factorybot](<https://devfeed.tech/tags/factorybot.md>), [flow-analytics](<https://devfeed.tech/tags/flow-analytics.md>), [rails](<https://devfeed.tech/tags/rails.md>), [ruby](<https://devfeed.tech/tags/ruby.md>), [software-testing](<https://devfeed.tech/tags/software-testing.md>), [testing](<https://devfeed.tech/tags/testing.md>)

### AI overview

A Rails testing tip explaining that model tests without a backing database table can fail when Rails tries to load an unintended fixture file. Deleting the fixture file prevents the test runner from querying the missing table; the article also notes that FactoryBot suppresses fixture creation.

### Source excerpt

I generate a lot of models without ActiveRecord backing. The reason for this is I try and follow a fairly functional style of Ruby coding where I use class methods. The reason I use models for this: I don't know what to call them other than a model The models directly is auto loaded so I can refresh it with reload! in Rails console My normal process for this: rails g foo Delete the migration Delete the "< ..." at the top i.e. the inherits from ActiveRecord stff; exact syntax varies from Rails version to Rails version Today I hit this error when running a test and it puzzled me: Error: VolumeCommonTest#test_it_should_have_the_right_values_for_cubic_feet_of_water: ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR: relation "volume_commons" does not exist LINE 9: WHERE a.attrelid = '"volume_commons"'::regclass This actually took me a bit to figure out. Here's the tldr: It was coming from bin/rails test test/models/volume_common.rb It was the result of the test runner trying to load the fixture file. The reason this was surprising was that I normally customize each Rails project with ThoughtBot's FactoryBot gem and this time I forgot. FactoryBot suppresses fixture file creation but since I screwed up, it was there and tried to get loaded into a missing table. And, yes, the error is mine since I didn't read it well but at times like these I wish for a gem called abusive_error messages which sees "PG::UndefinedTable" and shouts out something like: Yo! Hoser! Where be da database table ? Ah if there were only infinite time to craft the software tools we really want ...

## Fixing FactoryBot Validation Name Has Already Been Taken Controller Test or Spec Errors

DevFeed: [Fixing FactoryBot Validation Name Has Already Been Taken Controller Test or Spec Errors](<https://devfeed.tech/articles/fixing-factorybot-validation-name-has-already-been-taken-controller-test-or-spec-errors-28117.md>)

Original publisher: [Read original article](<http://fuzzyblog.io/blog/2022/06/10/fixing-factorybot-validation-name-has-already-been-taken-controller-test-or-spec-errors.html>)

Author: Fuzzygroup

Published: 2022-06-10T12:41:00Z

Content type: tutorial

Language: en

Sources: [Scott Johnson](<https://devfeed.tech/sources/scott-johnson.md>)

Topics: [Rails](<https://devfeed.tech/topics/rails.md>), [Testing](<https://devfeed.tech/topics/testing.md>), [Ruby](<https://devfeed.tech/topics/ruby.md>), [Development](<https://devfeed.tech/topics/development.md>)

Tags: [activerecord](<https://devfeed.tech/tags/activerecord.md>), [bug](<https://devfeed.tech/tags/bug.md>), [controllers](<https://devfeed.tech/tags/controllers.md>), [development](<https://devfeed.tech/tags/development.md>), [factorybot](<https://devfeed.tech/tags/factorybot.md>), [rails](<https://devfeed.tech/tags/rails.md>), [testing](<https://devfeed.tech/tags/testing.md>), [tests](<https://devfeed.tech/tags/tests.md>)

### AI overview

This troubleshooting article examines recurring ActiveRecord "Name has already been taken" failures in FactoryBot-backed Rails controller tests. It describes investigating associations, test data, database cleaning, and model accessors while tracing the source of the validation behavior.

### Source excerpt

So, last night, whilst pulling vampire hours on writing tests - always, always, always a bad idea - I encountered multiple variants on this bug: ❯ bundle exec rails test test/controllers/links_controller_test.rb:44 Running 7 tests in a single process (parallelization threshold is 50) Run options: --seed 21798 # Running: E Error: LinksControllerTest#test_should_get_edit: ActiveRecord::RecordInvalid: Validation failed: Name has already been taken test/controllers/links_controller_test.rb:47:in `block in <class:LinksControllerTest>' This was particularly vexing because while the object in question did have a name attribute, it did not have name validations: ######################################################################### # # validations # ######################################################################### validates_presence_of :project_id validates_presence_of :team_id validates_presence_of :account_id validates_presence_of :link_type_id There are a number of people on the internet that have this issue including this stack overflow post. What I noticed as I researched this is that I only saw it in controller tests. Also my model tests continued to function correctly without any validation issues. I had initially discovered this while working on my RodAuth testing deep dive and back burnered it until I got past that particularly nasty kettle of fix. I was working with two objects, link and project and project only through an association. So my Factory for link looked like this: FactoryBot.define do factory :link do url { "https://www.example.com/?time=#{Time.now.to_i}" } name { "Cartazzi App on development #{Time.now.to_i}" } active { true } association :account association :team association :project association :link_type end end You will notice the insane use of Time.now.to_i to try and generate more distinct data. This was an attempt to see if maybe some kind of hidden validation was present (it is ruby and everything is dynamic; who knows where a monk

## Warning in Rails Console Factory Bot Doesn't Seem to reload! Correctly

DevFeed: [Warning in Rails Console Factory Bot Doesn't Seem to reload! Correctly](<https://devfeed.tech/articles/warning-in-rails-console-factory-bot-doesn-t-seem-to-reload-correctly-28281.md>)

Original publisher: [Read original article](<http://fuzzyblog.io/blog/rails/2022/06/08/warning-in-rails-console-factory-bot-doesn-t-seem-to-reload-correctly.html>)

Author: Fuzzygroup

Published: 2022-06-08T12:13:00Z

Content type: tutorial

Language: en

Sources: [Scott Johnson](<https://devfeed.tech/sources/scott-johnson.md>)

Topics: [Rails](<https://devfeed.tech/topics/rails.md>), [Ruby](<https://devfeed.tech/topics/ruby.md>), [Development](<https://devfeed.tech/topics/development.md>)

Tags: [bug](<https://devfeed.tech/tags/bug.md>), [code](<https://devfeed.tech/tags/code.md>), [development](<https://devfeed.tech/tags/development.md>), [factorybot](<https://devfeed.tech/tags/factorybot.md>), [rails](<https://devfeed.tech/tags/rails.md>), [ruby](<https://devfeed.tech/tags/ruby.md>), [test](<https://devfeed.tech/tags/test.md>)

### AI overview

A developer documents a Rails console issue where FactoryBot object creation continued to fail after model changes and a reload!. Exiting and restarting the console resolved the behavior; the original error was caused by a missing belongs_to block in the model.

### Source excerpt

I'm actively engaged in greenfield development once again and I'm learning / relearning things that I likely have known in the past. I don't know if this is a known issue, a bug or maybe a design choice. Either way, I found it useful to know this so I thought it was useful to document it. I spend a lot of time in rails console (thank you Jared for beating this into me a thousand, thousand years ago; hope you are well) and reload! normally works pretty damn well but this one caught me hard. Take a look at this back trace link = FactoryBot::create(:link) TRANSACTION (0.1ms) BEGIN Account Create (0.2ms) INSERT INTO "accounts" ("email", "status", "role") VALUES ($1, $2, $3) RETURNING "id" [["email", "howard@watsica.com"], ["status", "verified"], ["role", "customer"]] Account::PasswordHash Create (0.2ms) INSERT INTO "account_password_hashes" ("id", "password_hash") VALUES ($1, $2) RETURNING "id" [["id", 63], ["password_hash", "[FILTERED]"]] TRANSACTION (0.5ms) COMMIT /Users/sjohnson/.rvm/gems/ruby-3.0.0/gems/activemodel-7.0.3/lib/active_model/attribute_methods.rb:458:in `method_missing': undefined method `account=' for #<Link id: nil, created_at: nil, updated_at: nil, date_created_at: nil, account_id: nil, team_id: nil, link_type_id: nil, active: true, url: "https://www.example.com/", name: "Cartazzi App on development", project_id: nil, code_environment_id: nil> (NoMethodError) Did you mean? account_id= 3.0.0 :014 > reload! Reloading... true 3.0.0 :015 > link = FactoryBot::create(:link) TRANSACTION (0.1ms) BEGIN Account Create (0.3ms) INSERT INTO "accounts" ("email", "status", "role") VALUES ($1, $2, $3) RETURNING "id" [["email", "chu_carter@schaden.name"], ["status", "verified"], ["role", "customer"]] Account::PasswordHash Create (0.3ms) INSERT INTO "account_password_hashes" ("id", "password_hash") VALUES ($1, $2) RETURNING "id" [["id", 64], ["password_hash", "[FILTERED]"]] TRANSACTION (0.5ms) COMMIT /Users/sjohnson/.rvm/gems/ruby-3.0.0/gems/activemodel-7.0.3/lib/activ

## Rails Console and Test Mode

DevFeed: [Rails Console and Test Mode](<https://devfeed.tech/articles/rails-console-and-test-mode-28263.md>)

Original publisher: [Read original article](<http://fuzzyblog.io/blog/rails/2020/02/19/rails-console-and-test-mode.html>)

Author: Fuzzygroup

Published: 2020-02-19T00:00:00Z

Content type: tutorial

Language: en

Sources: [Scott Johnson](<https://devfeed.tech/sources/scott-johnson.md>)

Topics: [Rails](<https://devfeed.tech/topics/rails.md>), [test](<https://devfeed.tech/topics/test.md>), [Testing](<https://devfeed.tech/topics/testing.md>)

Tags: [console](<https://devfeed.tech/tags/console.md>), [environment](<https://devfeed.tech/tags/environment.md>), [factorybot](<https://devfeed.tech/tags/factorybot.md>), [rails](<https://devfeed.tech/tags/rails.md>), [selenium](<https://devfeed.tech/tags/selenium.md>), [test](<https://devfeed.tech/tags/test.md>), [testing](<https://devfeed.tech/tags/testing.md>)

### AI overview

This short tutorial shows how to launch the Rails console in test mode with RAILS_ENV=test rails c. This lets developers inspect the test environment and work directly with FactoryBot to experiment with test factories.

### Source excerpt

This one is a short one but a good one. One really useful trick is to launch Rails console in test mode: ❯ RAILS_ENV=test rails c Running via Spring preloader in process 41705 Loading test environment (Rails 6.0.2.1) irb: warn: can't alias context from irb_context. You can check the Rails environment this way: 2.7.0 :001 > Rails.env "test" The benefit to this is that you can work directly with FactoryBot and experiment with factories: 2.7.0 :002 > project = FactoryBot.create(:project, name: "Scott's Project") FactoryBot is installed via Gemfile and locked into test environment only (which is why you need to launch Rails console in test mode): group :test do # Adds support for Capybara system testing and selenium driver gem "capybara", ">= 2.15" gem "selenium-webdriver" # Easy installation and use of web drivers to run system tests with browsers gem "webdrivers" gem 'factory_bot_rails' #gem 'database_cleaner' # gem 'shoulda' # gem 'shoulda-matchers' end

## Rails Test Basics

DevFeed: [Rails Test Basics](<https://devfeed.tech/articles/rails-test-basics-28258.md>)

Original publisher: [Read original article](<http://fuzzyblog.io/blog/rails/2020/01/27/rails-test-basics.html>)

Author: Fuzzygroup

Published: 2020-01-27T00:00:00Z

Content type: tutorial

Language: en

Sources: [Scott Johnson](<https://devfeed.tech/sources/scott-johnson.md>)

Topics: [Rails](<https://devfeed.tech/topics/rails.md>), [Testing](<https://devfeed.tech/topics/testing.md>), [RSpec](<https://devfeed.tech/topics/rspec.md>), [Development](<https://devfeed.tech/topics/development.md>)

Tags: [dockerignore-usage](<https://devfeed.tech/tags/dockerignore-usage.md>), [errors](<https://devfeed.tech/tags/errors.md>), [factorybot](<https://devfeed.tech/tags/factorybot.md>), [rails](<https://devfeed.tech/tags/rails.md>), [rspec](<https://devfeed.tech/tags/rspec.md>), [skip](<https://devfeed.tech/tags/skip.md>), [test](<https://devfeed.tech/tags/test.md>), [testing](<https://devfeed.tech/tags/testing.md>), [tests](<https://devfeed.tech/tags/tests.md>)

### AI overview

A practical guide to classical Rails testing for a project using standard Rails tests instead of RSpec. It covers debugging with byebug, skipping tests, running tests with Rails commands, interpreting a confusing zero-test result, using FactoryBot, and writing assertions.

### Source excerpt

More than a decade using RSpec has left me flummoxed in terms of "classical" Rails testing. I'm on a new project built using the Jumpstart application template and all the tests are standard Rails tests so here's a quick recap that I wrote, well, to force myself to step back in time and go "old school". And if you don't like my version then you should really read this. And if you are using Devise for authentication then you really must read this. Making Tests Debuggable The ability to use byebug in a testing context for breakpoints and stepping through code is utterly invaluable. Here's what you need to do for that: Add byebug into a development, test group in Gemfile. Add the line require 'byebug' to the very top of test_helper.rb How Do You Skip a Test? You put the keyword 'skip' at the top of the test that you need to skip. This is equivalent to xit in RSpec. Running Tests The very basic of testing is nothing more than test execution so to run all model tests: rails test test/models/ and to run one file rails test test/models/user_test.rb and to run everything: rails test and to run with verbose mode: rails test -v test/models and to run verbosely and fail on the first test failure: rails test -v -f test/helpers/application_helper.rb and to run just one specific test: rails test test/controllers/labels_controller_test.rb:9 Note: RSpec is very good at running the next test if the line number shifts a bit (example you put in :8 but you added a line so its actually :9). With standard rails test, you get this madness: ❯ rails test test/controllers/projects_controller_test.rb:17 Running via Spring preloader in process 95090 Run options: --seed 52687 # Running: Finished in 0.010622s, 0.0000 runs/s, 0.0000 assertions/s. 0 runs, 0 assertions, 0 failures, 0 errors, 0 skips The 0 runs, 0 assertions, 0 failures, 0 errors, 0 skips can best be interpreted as: Yo! Hoser! I don't know what to do here so I'm going to confuse you deliberately. Ha Haw! Death to Fixtures; Viva La F

## Ruby Testing Technique - The Power and Stupidity of def foo

DevFeed: [Ruby Testing Technique - The Power and Stupidity of def foo](<https://devfeed.tech/articles/ruby-testing-technique-the-power-and-stupidity-of-def-foo-28300.md>)

Original publisher: [Read original article](<http://fuzzyblog.io/blog/rspec/2020/01/03/ruby-testing-technique-the-power-and-stupidity-of-def-foo.html>)

Author: Fuzzygroup

Published: 2020-01-03T00:00:00Z

Content type: tutorial

Language: en

Sources: [Scott Johnson](<https://devfeed.tech/sources/scott-johnson.md>)

Topics: [Testing](<https://devfeed.tech/topics/testing.md>), [Ruby](<https://devfeed.tech/topics/ruby.md>), [Software Engineering](<https://devfeed.tech/topics/software-engineering.md>), [Rails](<https://devfeed.tech/topics/rails.md>), [Database](<https://devfeed.tech/topics/database.md>)

Tags: [activerecord](<https://devfeed.tech/tags/activerecord.md>), [database](<https://devfeed.tech/tags/database.md>), [factorybot](<https://devfeed.tech/tags/factorybot.md>), [rails](<https://devfeed.tech/tags/rails.md>), [rspec](<https://devfeed.tech/tags/rspec.md>), [ruby](<https://devfeed.tech/tags/ruby.md>), [testing](<https://devfeed.tech/tags/testing.md>), [validation](<https://devfeed.tech/tags/validation.md>)

### AI overview

A Ruby testing troubleshooting article describes debugging a failing FactoryBot factory for an Objective record in a Rails side project. The supplied excerpt identifies validation errors involving missing User and Organization associations and begins a technique of adding class and instance methods named foo to investigate the problem, but it ends before documenting the complete resolution.

### Source excerpt

I had an abysmal day yesterday coding on my side project. Ok - coding on one of my side projects. I had one of those days where you try to do something simple and NOTHING, NOT ONE DAMN THING, WORKS. Note: Every software engineer knows this type of day. They aren't days that you talk about with anyone in your life because you spend hours failing at something that you know is so damn simple that, if you can't make it work, you should honestly give up software engineering and go cut grass for a living. I refer to these days, when I have them, as spirit crushers / brain emasculators. And when they occur, I find that a nap (or a snickers bar) is the best medicine. All I was trying to do was make a simple factory work. For those who aren't deeply immersed in the world of software testing in ruby, a factory is a software method which creates a sample object that represents the actual object so it can be tested. Factories are used in place of actual objects, generally, because they run faster. Here was the definition of the factory: FactoryBot.define do factory :objective do name {Faker::Name.first_name} user organization objective_type okr_team quarter end end All this means is: Create an object named objective Give it a name attribute that is pulled from a library called Faker using the first_name method Give it a relationship back to the user object Give it a relationship back to the organization object Give it a relationship back to the objective_type object Give it a relationship back to the okr_team object Give it a relationship back to the quarter object Although this might seem complex, it is actually drop dead simple and something that I've probably done hundreds if not thousands of times. And yet, yesterday, all I could get was some variant on this censored backtrace: ActiveRecord::RecordInvalid: Validation failed: Organization must exist, User can't be blank, Organization can't be blank # /Users/sjohnson/.rvm/gems/ruby-2.6.5/gems/fabrication-2.21.0/lib/fabricatio

## Updating from FactoryGirl to FactoryBot

DevFeed: [Updating from FactoryGirl to FactoryBot](<https://devfeed.tech/articles/updating-from-factorygirl-to-factorybot-15935.md>)

Original publisher: [Read original article](<https://developer.squareup.com/blog/updating-from-factorygirl-to-factorybot>)

Author: David Haley

Published: 2017-11-14T02:02:45Z

Content type: article

Language: en

Sources: [Square Corner Blog RSS Feed](<https://devfeed.tech/sources/square-corner-blog-rss-feed.md>)

Topics: [Testing](<https://devfeed.tech/topics/testing.md>), [Ruby](<https://devfeed.tech/topics/ruby.md>)

Tags: [continuous-integration](<https://devfeed.tech/tags/continuous-integration.md>), [engineering](<https://devfeed.tech/tags/engineering.md>), [factorybot](<https://devfeed.tech/tags/factorybot.md>), [pull-request](<https://devfeed.tech/tags/pull-request.md>), [ruby](<https://devfeed.tech/tags/ruby.md>), [testing](<https://devfeed.tech/tags/testing.md>)

### AI overview

The article describes Square Payroll's migration from FactoryGirl to FactoryBot after ThoughtBot renamed the Ruby testing library in 2017. It explains the concerns about the former name and reports that the codebase update and review were completed quickly.

### Source excerpt

On October 24th, 2017 the ThoughtBot team renamed their popular Ruby testing library FactoryGirl to FactoryBot. They explained their...