在测试环境中动态构建 Active Record 模型(带表)
with_model dynamically builds an Active Record model (with table) before each test in a group and destroys it afterwards.
with_model is actively maintained. It is quite stable, so while updates may appear infrequent, it is only because none are needed.
Install as usual: gem install with_model or add gem 'with_model' to your Gemfile. See .github/workflows/ci.yml for supported (tested) Ruby versions.
Choose the entrypoint for the test runner that owns the declarations. Each performs complete global setup for one runner; see its guide for lifecycle and manual-setup details.
require "with_model/rspec"See the RSpec guide.
require "with_model/minitest"See the Minitest guide.
require "with_model/test_unit"See the Test::Unit guide.
Plain require "with_model" remains framework-neutral. For manual setup,
select a runner and extend its test context directly:
require "minitest"
require "with_model"
WithModel.runner = :minitest
Minitest::Test.extend WithModelRSpec uses RSpec.configure { |config| config.extend WithModel }; Test::Unit
uses Test::Unit::TestCase.extend WithModel. A declaration can override the
global runner when needed:
with_model :Post, runner: :test_unit do
table
endLoading multiple convenience entrypoints in one process is unsupported because
the last one changes the global runner. For mixed runners, use plain
with_model, direct extension, and explicit runner: options.
After setting up as above, call with_model and inside its block pass it a table block and a model block.
…Pass table(false) to create no table at all. Active Record's own inheritance
then supplies the superclass's table, which is what single table inheritance
needs.
The superclass can be another with_model model. Its constant does not exist yet
when the superclass: argument is read, so name it with a String or a Symbol, or
pass a callable returning it, and it will be resolved once per example.
describe "with_model supports Single Table Inheritance" do
with_model :Sandwich do
table do |t|
t.string "type"
t.string "bread"
end
end
with_model :ChunkyBacon, superclass: :Sandwich do
table(false)
end
it "shares the superclass's table" do
expect(ChunkyBacon.table_name).to eq Sandwich.table_name
end
it "stores its own type" do
sandwich = ChunkyBacon.create!(bread: "rye")
expect(sandwich.reload.type).to eq "ChunkyBacon"
expect(Sandwich.first).to be_a ChunkyBacon
end
endA superclass: that cannot be used raises WithModel::InvalidSuperclass: one
that is not an Active Record class, one with no table of its own
(ActiveRecord::Base, or an abstract class such as a Rails app's
ApplicationRecord), or one whose table has no inheritance column to tell a
subclass's rows apart. A name that resolves to nothing raises
WithModel::MissingSuperclass, a kind of InvalidSuperclass, quoting the
constant Ruby could not find — for a namespaced name, that is the segment which
is actually missing. Both are ArgumentErrors.
A superclass whose table does not exist yet is allowed, since the table may be created later in the example, and Active Record reports its absence clearly enough on its own. Rows the model wrote are deleted when it goes away, since they name a class that is about to stop existing and would make the superclass unloadable.
foreign_key: true asks Active Record to infer the table a foreign key points
at, and it infers authors from author_id. Generated table names are unique
rather than conventional, so name the table instead:
describe "with_model supports foreign keys" do
with_model :Author do
table
end
with_model :Book do
table do |t|
t.references :author, foreign_key: {to_table: Author.table_name}
end
model do
belongs_to :author
end
end
it "has a foreign key" do
expect { Book.create!(author_id: 0) }
.to raise_error ActiveRecord::InvalidForeignKey
end
endThis reads Author.table_name, so declare Author first: models are created in
the order they are declared, and destroyed in the reverse order.
See the gemspec metadata for Ruby and
Active Record requirements. RSpec, Minitest, and Test::Unit are optional
consumer framework dependencies; install the framework used by its selected
entrypoint. Requiring a selected entrypoint without its framework installed
raises the framework's ordinary LoadError.
scope: is RSpec-only and is silently ignored by Minitest and Test::Unit.
with_model/WithModel::Model.new. This allows with_model (when limited to this API) to run concurrently (in processes or threads) with a single database schema. While there is a possibility of collision, it is very small.with_table/WithModel::Table.new. This may cause collisions at runtime if tests are run concurrently against a single database schema, unless the caller takes care to ensure the table names passed as arguments are unique across threads/processes.In general, with_model is not guaranteed to be thread-safe, but is, in certain usages, safe to use concurrently across multiple processes with a single database schema.
Bug reports and pull requests are welcome. See the CONTRIBUTING guide for how to run the tests against a particular Ruby or Active Record.
with_model uses Semantic Versioning 2.0.0.
Copyright © 2010–2026 Casebook PBC. Licensed under the MIT license, see LICENSE file.
暂无开放 Issues,或尚未同步最近议题。