百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
W

with_model

> 测试质量
开源

在测试环境中动态构建 Active Record 模型(带表)

197 stars0 点赞4 次浏览
访问官网GitHub

工具介绍

在测试环境中动态构建 Active Record 模型(带表)

with_model

with_model dynamically builds an Active Record model (with table) before each test in a group and destroys it afterwards.

Development status

with_model is actively maintained. It is quite stable, so while updates may appear infrequent, it is only because none are needed.

Installation

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.

Test runner setup

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.

RSpec

ruby
require "with_model/rspec"

See the RSpec guide.

Minitest

ruby
require "with_model/minitest"

See the Minitest guide.

Test::Unit

ruby
require "with_model/test_unit"

See the Test::Unit guide.

Advanced and mixed-runner setup

Plain require "with_model" remains framework-neutral. For manual setup, select a runner and extend its test context directly:

ruby
require "minitest"
require "with_model"

WithModel.runner = :minitest
Minitest::Test.extend WithModel

RSpec uses RSpec.configure { |config| config.extend WithModel }; Test::Unit uses Test::Unit::TestCase.extend WithModel. A declaration can override the global runner when needed:

ruby
with_model :Post, runner: :test_unit do
  table
end

Loading 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.

Usage

After setting up as above, call with_model and inside its block pass it a table block and a model block.

…

Single table inheritance

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.

ruby
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
end

A 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 keys

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:

ruby
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
end

This reads Author.table_name, so declare Author first: models are created in the order they are declared, and destroyed in the reverse order.

Requirements

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.

Thread-safety

  • A unique table name is used for tables generated via 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.
  • A user-supplied table name is used for tables generated via 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.
  • Generated models are created in stubbed constants, which are global; no guarantee is made to the uniqueness of a constant, and this may be unsafe.
  • Generated classes are Active Record subclasses:
    • This library makes no guarantee as to the thread-safety of creating Active Record subclasses concurrently.
    • This library makes no guarantee as to the thread-safety of cleaning up Active Record/Active Support’s internals which are polluted upon class creation.

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.

Contributing

Bug reports and pull requests are welcome. See the CONTRIBUTING guide for how to run the tests against a particular Ruby or Active Record.

Versioning

with_model uses Semantic Versioning 2.0.0.

License

Copyright © 2010–2026 Casebook PBC. Licensed under the MIT license, see LICENSE file.

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

Rubyactiverecordminitestrspecruby

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月18日
分类测试质量
定价开源

> 相关工具

J
Jest
JavaScript 测试框架
P
Playwright
现代端到端测试框架
E
eslint-plugin-test-selectors
Enforces that data-test-id attributes are added to interactive DOM elements (JSX) to help with UI testing. JSX only.