skip to content

Testing Setup & Styles

Rails' own test support: test types and bin/rails test, YAML fixtures, factory_bot, rspec-rails spec types, Capybara system tests and test helpers. Interviewers probe how a suite is built.

part ofRuby on Railsread it →
on this pageshow

explore

questions

30

With factory_bot, how do build, create, build_stubbed and attributes_for differ, and which of them write to the database?

level: juniorimportance: must knowfreq 70%

answer

  1. only create calls save!
  2. build builds its associations too
  3. build_stubbed fakes an id from 1001
  4. attributes_for drops associations
  5. create_list and build_pair

basics

~20 s

Only create writes: it builds the object and calls save!. build returns an unsaved instance, build_stubbed an unsaved one that pretends to be persisted with a fake id, and attributes_for a plain hash without associations.

solid answer

~40 s

With factory_bot, `build(:order)` instantiates the model and assigns attributes without saving. Because `FactoryBot.use_parent_strategy` defaults to `true`, its associations are built too. `create(:order)` does the same and then calls `save!`, so validations and model callbacks run, an invalid factory raises `ActiveRecord::RecordInvalid`, and associations are created first. `build_stubbed(:order)` never touches the database. It assigns a fake id (counting up from 1001), makes `persisted?` return true, fills timestamps, stubs its associations as well, and raises if you call `save`, `update` or `reload`. `attributes_for(:order)` returns a hash of attribute values with declared associations left out, which suits request params. Each strategy has `_list` and `_pair` forms, such as `create_list(:order, 3)`.

code

ruby · 11 lines
ruby
order = build(:order)
order.new_record?            # => true
order.customer.new_record?   # => true (use_parent_strategy)

stubbed = build_stubbed(:order)
stubbed.id                   # => 1001
stubbed.persisted?           # => true
stubbed.save                 # raises RuntimeError

attributes_for(:order)       # => { number: "BM-00007", notes: nil }
create_list(:line_item, 3, order: create(:order))

go deeper

for a junior

Know that create saves with save!, build does not, build_stubbed fakes persistence, and attributes_for returns a hash for params.

for a middle

Explain use_parent_strategy, why create raises RecordInvalid for a bad factory, and what build_stubbed overrides and refuses.

for a senior

Choose the cheapest strategy per test, and spot when a build still writes because of association strategy settings.

for a principal

Set suite-wide strategy conventions, such as stubbed by default for presenters, so test speed holds as factories grow.

## Four strategies, one factory A **factory** in factory_bot describes how to make one kind of object. The **strategy** you call decides what happens to the result: | Call | Returns | Database writes | Associations | |---|---|---|---| | `build(:order)` | unsaved `Order` | none | built with the same strategy | | `create(:order)` | saved `Order` | `INSERT` via `save!` | created first | | `build_stubbed(:order)` | unsaved `Order` that claims to be persisted | none | stubbed | | `attributes_for(:order)` | `Hash` of attributes | none | left out of the hash | Each one also has a list and a pair form: `create_list(:line_item, 3, order: order)`, `build_pair(:order)`, `build_stubbed_list(:order, 5)`. ## build - Calls the model's constructor, assigns the attributes and runs `after(:build)` callbacks. - Nothing is saved, so model validations have not run, and `new_record?` is true. - Since factory_bot 5, **`FactoryBot.use_parent_strategy` is `true`**: an association declared in the factory follows the parent's strategy. `build(:line_item)` therefore builds, not creates, its `order` and `product`. A per-association `strategy: :create` overrides this. ## create - Does everything `build` does, then runs `before(:create)`, persists the object with the factory's `to_create`, which defaults to `save!`, then runs `after(:create)`. - Because it is `save!`, the model's validations and Active Record callbacks run, and an invalid factory raises `ActiveRecord::RecordInvalid` at the call site. - Associations are created first, so `create(:line_item)` can insert an order, a customer, a product and a band. ## build_stubbed - Never opens a connection for the object itself. It assigns an id from a counter (1001, 1002 and so on, or a UUID for UUID keys), sets `created_at` and `updated_at`, and clears change tracking. - Overrides `persisted?` to return `true`, `new_record?` to return `false`, and `destroyed?` to return `false`, so `order_path(order)` and `form_with(model: order)` behave as for a saved record. - Replaces `save`, `save!`, `update`, `destroy`, `reload`, `touch`, `update_column` and similar methods with ones that raise a `RuntimeError` ("stubbed models are not allowed to access the database"). - Associations declared in the factory are stubbed too, whatever `use_parent_strategy` says. - It is the fastest choice for presenters, helpers, policies and anything that only reads attributes. ## attributes_for - Returns a hash such as `{ number: "BM-00042", notes: nil }`. - Declared associations and transient attributes are left out, so `post orders_url, params: { order: attributes_for(:order) }` sends no `customer_id`. Merge it yourself: `attributes_for(:order).merge(customer_id: customer.id)`. - Inline associations written as `customer { association :customer }` appear in the hash as `nil`. ## Picking one 1. Need the row in the database, because a query, a uniqueness check or a request reads it? Use `create`. 2. Need a model object, and nothing reads it back from the database? Use `build`, or `build_stubbed` when the code also asks `persisted?` or needs an id. 3. Need form params? Use `attributes_for`, plus the foreign keys. Defaulting to `create` everywhere is the most common cause of slow suites, because every call writes the whole association graph. ## Customising what create does The persistence step is configurable per factory, which matters for objects that are not plain Active Record rows: - `to_create { |instance| instance.save!(validate: false) }` replaces the default `save!`. Use it sparingly, because it lets invalid records into the database just as fixtures do. - `skip_create` makes `create` behave like `build` for objects that have nowhere to be saved, such as a plain Ruby value object. - `initialize_with { new(order, currency: "EUR") }` changes how the object is constructed, for classes whose constructor takes arguments. - `FactoryBot.build_stubbed_starting_id = 5000` moves the stubbed id counter, which helps when fake ids would collide with ids that a test also creates for real. ## A quick way to remember them | Question the test asks | Strategy | |---|---| | "Is this row in the database?" | `create` | | "Does this object compute the right thing?" | `build` | | "Does this view or presenter treat it as saved?" | `build_stubbed` | | "What would the form post?" | `attributes_for` |

  • Why might build(:line_item) still insert rows in an older factory_bot suite?
    Before factory_bot 5, associations defaulted to `create` even when the parent was built, and some suites keep that by setting `FactoryBot.use_parent_strategy = false`. A factory can also force it per association with `association :order, strategy: :create`. Either way `build` writes the parents, so check the setting and the factory before assuming `build` is free.
  • When does build_stubbed break a test that build would pass?
    When the code under test persists or reloads the object, for example calling `update` or `reload`. The stubbed methods raise a `RuntimeError`. Reading a `has_many` collection on a stubbed record also misses, because the fake id matches no rows. Use `build_stubbed` for code that only reads the object's own attributes and its stubbed `belongs_to` targets.

  • build saves the record but skips validations.
  • create inserts rows with SQL and skips the model's callbacks.
  • build_stubbed objects return false from persisted? and have a nil id.
  • attributes_for includes the customer_id of the associated record.
  • build(:line_item) always creates its order in the database.

Assumes factory_bot 6.6 through factory_bot_rails 6.5 on Rails 8.1; use_parent_strategy has defaulted to true since factory_bot 5.0.

open as a page

In a Rails app, how are YAML fixtures in test/fixtures loaded into the test database, and what does teams(:riverside) return inside a test?

level: juniorimportance: must knowfreq 62%

basics

~10 s

Each test/fixtures/*.yml file holds labelled rows for one table; fixtures :all in test_helper.rb inserts them before the tests run, and teams(:riverside) returns the Team record with that label, loaded from the database.

open as a page

In a Rails test, what does assert_difference check, and how do you assert that a sign-up creates one User and one Session?

level: juniorimportance: must knowfreq 58%

basics

~20 s

assert_difference evaluates an expression, runs the block, evaluates it again and asserts the change equals the expected difference, 1 by default. A hash checks several counts: assert_difference({ "User.count" => 1, "Session.count" => 1 }) { post sign_up_path, params: ... }.

open as a page

In a Rails 8.1 app, how do you add and run a system test, and what does ApplicationSystemTestCase with driven_by set up?

level: juniorimportance: must knowfreq 56%

basics

~10 s

A system test subclasses ApplicationSystemTestCase, which inherits ActionDispatch::SystemTestCase and calls driven_by :selenium, using: :headless_chrome. bin/rails generate system_test creates both files in Rails 8.1, and bin/rails test:system runs them; plain bin/rails test skips them.

open as a page

In a Rails 8.1 app, when do you subclass ActiveSupport::TestCase, ActionDispatch::IntegrationTest or ActionController::TestCase, and what does each exercise?

level: juniorimportance: must knowfreq 68%

basics

~20 s

ActiveSupport::TestCase is the base for model and plain-Ruby tests; ActionDispatch::IntegrationTest sends requests through routing, middleware, controller and view, and is what Rails generates for controller tests; ActionController::TestCase dispatches one action directly and is the legacy style.

open as a page

For a Rails test suite, when do YAML fixtures beat factory_bot factories, and when do factories win?

level: middleimportance: must knowfreq 58%

basics

~20 s

Fixtures win on speed and shared, named reference data, since they load once and roll back; factories win when each test needs its own explicit, valid variations, at the cost of inserts in every test and possible cascades.

open as a page

In a Rails integration test, how do you assert that a sign-up enqueues a welcome email, and when does assert_emails count it?

level: middleimportance: must knowfreq 50%

basics

~20 s

Use assert_enqueued_email_with WelcomeMailer, :welcome, params: { user: user } to check the deliver_later job. assert_emails with a block performs the mail jobs enqueued inside it and counts deliveries, while assert_emails without a block only counts ActionMailer::Base.deliveries so far.

open as a page

With rspec-rails 8, why do request specs replace controller specs for a time-sheet JSON API, and what does each one exercise?

level: middleimportance: must knowfreq 68%

basics

~20 s

Request specs send a real verb and path through Rails' router, middleware and controller, like ActionDispatch::IntegrationTest. Controller specs call one action directly. Since RSpec 3.5 both teams recommend request specs; assigns and render_template need the rails-controller-testing gem.

open as a page

With Capybara in a Rails system test, which finders and assertions wait for the page, and which read it once and race the browser?

level: middleimportance: must knowfreq 55%

basics

~20 s

Capybara's find, assert_selector, assert_text, assert_no_selector and assert_current_path retry for up to default_max_wait_time, 2 seconds. Plain reads such as page.current_path, element.text compared with ==, refute has_css? or counting all(...) do not wait for the expected state.

open as a page

How do you add factory_bot_rails to a Rails 8.1 app so create(:order) works in Minitest, and where are factory definitions loaded from?

level: juniorimportance: should knowfreq 36%

basics

~10 s

Add factory_bot_rails to the development and test groups, include FactoryBot::Syntax::Methods in ActiveSupport::TestCase, and put definitions in test/factories; the railtie loads factories.rb and factories/*.rb under the app root, test/ and spec/.

open as a page

In a Rails 8.1 app, what does bin/rails generate rspec:install create, and why do Rails specs require rails_helper instead of spec_helper?

level: juniorimportance: should knowfreq 46%

basics

~10 s

rspec:install writes .rspec, spec/spec_helper.rb and spec/rails_helper.rb. spec_helper configures plain RSpec without Rails; rails_helper loads config/environment, requires rspec/rails and sets fixtures and transactions, so any spec touching Rails code requires rails_helper.

open as a page

In a Rails integration test, how do assert_response and follow_redirect! verify a booking form that redirects after a successful POST?

level: juniorimportance: should knowfreq 55%

basics

~10 s

assert_response :redirect passes for any 3xx and assert_redirected_to checks the Location; follow_redirect! then requests that Location with GET (keeping the verb on 307/308) and returns the new status for assert_response :success.

open as a page

In a factory_bot factory for a merch-store order, how do traits, sequences, transient attributes and after(:create) build a paid order with line items?

level: middleimportance: should knowfreq 52%

basics

~20 s

A sequence gives each order a unique number, trait :paid adds the payment attributes, and a transient line_items_count read in after(:create) |order, evaluator| calls create_list for the items; create(:order, :paid, :with_line_items, line_items_count: 2) combines them.

open as a page

In Rails YAML fixtures, how do label references and ActiveRecord::FixtureSet.identify fill foreign keys for belongs_to, polymorphic and has_many :through rows?

level: middleimportance: should knowfreq 45%

basics

~20 s

Rails derives each row's id from its label with ActiveRecord::FixtureSet.identify, so team: riverside becomes team_id = identify(:riverside); polymorphic refs add (Type), and has_many :through or HABTM lists like matches: opening_day, derby write the join rows.

open as a page

Because Rails inserts YAML fixtures with raw SQL, which model behaviour do the rows skip, and how do ERB, DEFAULTS and enum labels help keep them valid?

level: middleimportance: should knowfreq 33%

basics

~20 s

Fixture rows skip validations, callbacks and model-level attribute defaults, so they hold exactly what the YAML says; enum labels are translated, DEFAULTS anchors share values, and ERB computes values once at load time, so a validity test over all fixtures catches drift.

open as a page

In Rails' Minitest helpers, how do assert_enqueued_with, perform_enqueued_jobs and assert_performed_jobs differ, and why might a model test lack them?

level: middleimportance: should knowfreq 45%

basics

~20 s

assert_enqueued_with checks that a job with given class, args, queue or time was enqueued; perform_enqueued_jobs runs enqueued jobs; assert_performed_jobs counts jobs that ran. They live in ActiveJob::TestHelper, which integration, job and mailer tests include but plain model tests do not.

open as a page

In a Rails test, how do travel_to, travel and freeze_time control time to check that a seven-day trial ends, and what do they not stub?

level: middleimportance: should knowfreq 52%

basics

~20 s

travel_to(time), travel(duration) and freeze_time stub Time.now, Date.today and DateTime.now so the clock stops at the chosen instant, and Rails undoes the stubs after each test. Database functions like NOW(), other processes and the browser keep real time.

open as a page

In rspec-rails, how do the have_enqueued_job and have_been_enqueued matchers differ, and what must the Active Job adapter be for either to work?

level: middleimportance: should knowfreq 44%

basics

~20 s

have_enqueued_job is a block matcher counting jobs enqueued inside expect { }; have_been_enqueued checks a job class against everything the adapter holds. Both raise unless ActiveJob::Base.queue_adapter is the test adapter, which a Rails test environment uses when nothing else is configured.

open as a page

In rspec-rails 8, how does a spec get its type, and what breaks when infer_spec_type_from_file_location! stays commented out?

level: middleimportance: should knowfreq 38%

basics

~20 s

rspec-rails mixes helpers into an example group by its type: metadata. New rails_helper files leave infer_spec_type_from_file_location! commented out, so a spec in spec/requests without type: :request has no get or post and fails with NoMethodError.

open as a page

In a Rails system test, when would you use driven_by :rack_test instead of driven_by :selenium, using: :headless_chrome, and what stops working?

level: middleimportance: should knowfreq 42%

basics

~20 s

driven_by :rack_test drives the app through Rack in the test process, with no browser, server thread or JavaScript, so it is fast for server-rendered pages. Anything needing JavaScript, such as Stimulus, Turbo, confirm dialogs or screenshots, needs Selenium with headless Chrome.

open as a page

With bin/rails test in Rails 8.1, how do you run one test by line, by name, or by folder, and what does a bare run skip?

level: middleimportance: should knowfreq 42%

basics

~20 s

bin/rails test takes paths with :line or :start-end suffixes and folders, filters by name with -i (Rails turns a test description into its method name), warns on -n, and by default skips test/system, which test:all includes.

open as a page

A Rails suite using factory_bot slowed down because create(:line_item) inserts a chain of parent records; how do you find the cascade and cut it?

level: seniorimportance: should knowfreq 38%

basics

~20 s

Count factory runs per name and strategy by subscribing to factory_bot.run_factory (and before_run_factory for the call stack), then pass shared parents into create_list, move optional associations into traits, and use build or build_stubbed where no row is needed.

open as a page

With Rails transactional tests, how are fixtures loaded once and rolled back per test, and when do you turn use_transactional_tests off?

level: seniorimportance: should knowfreq 40%

basics

~20 s

With use_transactional_tests (default true) Rails inserts fixtures once, then wraps each test in a transaction on a pinned connection and rolls it back; turn it off for code that needs top-level transactions or other connections, and fixtures then reload per test.

open as a page

A Rails 8.1 sign-up schedules TrialExpiryJob seven days out; how do you test that it is scheduled and that running it ends the trial at the right time?

level: seniorimportance: should knowfreq 32%

basics

~20 s

Assert the schedule with assert_enqueued_with(job: TrialExpiryJob, at: 7.days.from_now) around the sign-up. The test adapter performs scheduled jobs immediately, so travel past the deadline, run perform_enqueued_jobs and assert the trial ended; running it early must change nothing.

open as a page

In an rspec-rails suite, what does config.use_transactional_fixtures = true do to each example, and which cases still leave rows behind or need it off?

level: seniorimportance: should knowfreq 34%

basics

~20 s

use_transactional_fixtures = true wraps every example in a database transaction that is rolled back afterwards, sharing one pinned connection across threads. Rows written in before(:context), by another process or by code needing separate connections escape it; those cases need it off.

open as a page

A Rails system test that releases a held cinema seat behind a confirm dialog fails one CI run in ten; how do you diagnose and fix it?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Wrap the click in accept_confirm("Release seat B7?") so Capybara handles the dialog, then assert the outcome with a waiting matcher such as assert_selector before touching the database. Read the failure screenshot and HTML in tmp/screenshots, and remove sleeps.

open as a page

In a Rails system test, where does the application run, and what follows from the test and the Puma server sharing one process?

level: seniorimportance: should knowfreq 30%

basics

~20 s

Capybara boots the app on Puma in a thread of the test process, and the browser reaches it over HTTP. Test and server share the database connection, stubs and time travel, but run concurrently, so tests must wait for the server.

open as a page

In a Rails 8.1 suite using parallelize(workers: :number_of_processors), how does each forked worker get its own database, and what shared state can still make tests flaky?

level: seniorimportance: should knowfreq 38%

basics

~20 s

Rails forks one process per worker and, after each fork, appends the worker number to every test database name and loads the schema there; files, external caches and services stay shared, so isolate them in parallelize_setup.

open as a page

In a Rails 8.1 app built with the authentication generator, what does sign_in_as do in an integration test, and why can't a system test call it?

level: middleimportance: nice to knowfreq 22%

basics

~20 s

sign_in_as(user) creates a Session row for the user, sets Current.session and writes a signed session_id cookie into the integration test's cookie jar. It is included only into ActionDispatch::IntegrationTest, so system tests sign in through the login form instead.

open as a page

In a Rails 8.1 app, what do bin/ci and config/ci.rb run, and how does one failing step affect the rest of the run?

level: middleimportance: nice to knowfreq 24%

basics

~20 s

bin/ci loads ActiveSupport::ContinuousIntegration and runs the steps declared in config/ci.rb (setup, RuboCop, audits, Brakeman, bin/rails test, seeds); a failing step is reported but later steps still run, and the script exits non-zero at the end.

open as a page