mcpField
M
minitest

minitest

github.com/thinkoodle测试与质量7211 次安装8 周前更新
代码仓库

关于 minitest

minitest 是面向 Rails 项目的 Minitest 测试编写技能,适用于新增、迁移和优化测试。它强调使用 fixtures、减少数据库和浏览器开销,并通过验证行为而非实现来降低脆弱性。

主要功能

  1. 01按 Rails 测试类型组织测试
  2. 02优先使用 fixtures 与最少数据
  3. 03编写关注行为的稳定断言
  4. 04提供 RSpec 到 Minitest 的映射
  5. 05涵盖多租户与权限测试
  6. 06给出测试提速和调试建议

适用场景

  1. 01为模型、请求或策略编写 Minitest
  2. 02将 RSpec 测试迁移到 Minitest
  3. 03排查缓慢或不稳定的测试套件
  4. 04为 Rails 项目制定测试驱动流程

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/thinkoodle/rails-skills --skill minitest

安装后在 Claude Code 中输入/minitest确认已加载。

附带文件reference.md

详细介绍

Rails Minitest 专家

使用 Minitest 和 fixture 为 Rails 应用编写高性能、易维护且不脆弱的测试。

理念

核心原则:

  1. 测试行为,而非实现 - 关注代码做什么,而不是如何实现
  2. 快速反馈循环 - 优先选择单元测试而非集成测试,优先使用 fixture 而非工厂
  3. 测试即文档 - 测试名称应描述预期行为
  4. 尽量减少测试数据 - 只创建必要的数据;2 条记录就足够代表很多条记录
  5. 使用不脆弱的断言 - 测试结果,而非可能变化的确切值

测试金字塔:

    /\     System Tests (Few - critical paths only)
   /  \    
  /____\   Request/Integration Tests (Some)
 /      \  
/________\ Unit Tests (Many - models, policies, services)

何时使用此技能

  • 为 Rails 模型、策略、控制器或请求编写新的 Minitest 测试
  • 将 RSpec 测试转换为 Minitest
  • 调试运行缓慢或不稳定的测试
  • 提升测试套件性能
  • 遵循 Rails 测试惯例
  • 编写基于 fixture 的测试数据
  • 实施 TDD 工作流

指南

步骤 1:确定测试类型

编写测试前,先确定合适的测试类型:

测试类型位置适用场景
模型test/models/验证、关联、业务逻辑方法
策略test/policies/Pundit 授权策略
请求test/requests/完整的 HTTP 请求/响应周期
控制器test/controllers/控制器操作(优先使用请求测试)
系统test/system/使用真实浏览器测试关键用户流程
服务test/services/服务对象和复杂操作
作业test/jobs/后台作业行为
邮件程序test/mailers/电子邮件内容和发送
步骤 2:检查现有模式

务必先搜索现有测试:

# Find similar test files
rg "class.*Test < " test/

# Find existing fixtures
ls test/fixtures/

# Check for test helpers
cat test/test_helper.rb
cat test/support/*.rb

遵循项目现有惯例 - 保持一致比采用“最佳”模式更重要。

步骤 3:使用 fixture(而非工厂)

fixture 的速度比 Factory Bot 快 10-100 倍。

# AVOID - Factory Bot (slow, implicit)
let(:user) { create(:user) }
let(:project) { create(:project, workspace: workspace) }

# PREFER - Fixtures (fast, explicit)
setup do
  @workspace = workspaces(:main_workspace)
  @user = users(:admin_user)
  @project = projects(:active_project)
end

Fixture 最佳实践:

  • 创建用途明确且名称清晰的 fixture
  • 使用 <%= %> 生成动态值和 UUID
  • 通过 fixture 名称而非 ID 引用关联
  • 保持 fixture 精简 - 只包含必需属性
# test/fixtures/users.yml
admin_user:
  id: <%= Digest::UUID.uuid_v5(Digest::UUID::OID_NAMESPACE, "admin_user") %>
  email: "[email protected]"
  name: "Admin User"
  created_at: <%= 1.week.ago %>

member_user:
  id: <%= Digest::UUID.uuid_v5(Digest::UUID::OID_NAMESPACE, "member_user") %>
  email: "[email protected]"
  name: "Member User"
  workspace: main_workspace  # Reference by fixture name
步骤 4:编写测试结构

标准测试结构:

require "test_helper"

class ModelTest < ActiveSupport::TestCase
  setup do
    # Load fixtures - MINIMAL setup only
    @record = models(:fixture_name)
  end

  # Group related tests with comments or test naming
  
  # Validation tests
  test "requires name" do
    @record.name = nil
    refute @record.valid?
    assert_includes @record.errors[:name], "can't be blank"
  end

  # Method tests
  test "#full_name returns formatted name" do
    @record.first_name = "John"
    @record.last_name = "Doe"
    assert_equal "John Doe", @record.full_name
  end
end
步骤 5:遵循性能指南

尽可能避免数据库操作:

# SLOW - Creates database records
test "validates email format" do
  user = User.create!(email: "invalid", name: "Test")
  refute user.valid?
end

# FAST - Uses in-memory object
test "validates email format" do
  user = User.new(email: "invalid", name: "Test")
  refute user.valid?
end

尽量减少创建的记录:

# SLOW - Creates 25 records
test "paginates results" do
  create_list(:post, 25)
  # ...
end

# FAST - Configure pagination threshold for tests
# config/environments/test.rb: Pagy::DEFAULT[:limit] = 2
test "paginates results" do
  # Only need 3 records to test pagination with limit of 2
  assert_operator posts.count, :>=, 3
  # ...
end

尽可能避免浏览器测试:

# SLOW - Full browser simulation
class PostsSystemTest < ApplicationSystemTestCase
  test "creates a post" do
    visit new_post_path
    fill_in "Title", with: "Test"
    click_on "Create"
    assert_text "Post created"
  end
end

# FAST - Request test (no browser)
class PostsRequestTest < ActionDispatch::IntegrationTest
  test "creates a post" do
    post posts_path, params: { post: { title: "Test" } }
    assert_response :redirect
    follow_redirect!
    assert_response :success
  end
end
步骤 6:编写不脆弱的断言

测试行为,而非确切值:

# BRITTLE - Exact timestamp match
assert_equal "2025-01-15T10:00:00Z", response["created_at"]

# ROBUST - Just verify presence
assert response["created_at"].present?

# BRITTLE - Exact error message
assert_equal "Name can't be blank", record.errors.full_messages.first

# ROBUST - Check for key content
assert_includes record.errors[:name], "can't be blank"

使用包含式断言:

# BRITTLE - Exact match
assert_equal({ id: 1, name: "Test", email: "[email protected]" }, response)

# ROBUST - Check key attributes only
assert_equal 1, response[:id]
assert_equal "Test", response[:name]
# OR
assert response.slice(:id, :name) == { id: 1, name: "Test" }
步骤 7:处理多租户

对于使用 acts_as_tenant 的项目,务必在租户上下文中执行:

# WRONG - Missing tenant context
test "admin can view project" do
  assert policy(@admin, @project).show?
end

# CORRECT - Proper tenant scoping
test "admin can view project" do
  with_workspace(@workspace) do
    assert policy(@admin, @project).show?
  end
end
步骤 8:正确测试权限流程

务必先测试拒绝,再授予权限,之后测试允许:

test "member requires permission to create" do
  with_workspace(@workspace) do
    # 1. Test denial WITHOUT permission
    refute policy(@member, Project).create?
    
    # 2. Grant permission
    set_workspace_permissions(@member, @workspace, :allowed_to_create_projects)
    
    # 3. Test allow WITH permission
    assert policy(@member, Project).create?
  end
end

快速参考

断言对照(RSpec 到 Minitest)
RSpecMinitest
expect(x).to eq(y)assert_equal y, x
expect(x).to be_truthyassert x
expect(x).to be_falseyrefute x
expect(x).to be_nilassert_nil x
expect(arr).to include(x)assert_includes arr, x
expect(arr).not_to include(x)refute_includes arr, x
expect { }.to change { X.count }.by(1)assert_difference "X.count", 1 do ... end
expect { }.to raise_error(E)assert_raises(E) { ... }
expect(x).to be_validassert x.valid?
expect(x).not_to be_validrefute x.valid?
expect(x).to match(/pattern/)assert_match /pattern/, x
Rails 专用断言
# Record changes
assert_difference "Post.count", 1 do
  Post.create!(title: "Test")
end

assert_no_difference "Post.count" do
  Post.new.save  # Invalid, doesn't save
end

# Value changes
assert_changes -> { post.reload.title }, from: "Old", to: "New" do
  post.update!(title: "New")
end

# Response assertions
assert_response :success
assert_response :redirect
assert_redirected_to post_path(post)

# DOM assertions
assert_select "h1", "Expected Title"
assert_select ".post", count: 3

# Query assertions
assert_queries_count(2) { User.find(1); User.find(2) }
assert_no_queries { cached_value }
测试文件模板

模型测试:

require "test_helper"

class UserTest < ActiveSupport::TestCase
  setup do
    @user = users(:active_user)
  end

  test "valid fixture" do
    assert @user.valid?
  end

  test "requires email" do
    @user.email = nil
    refute @user.valid?
    assert_includes @user.errors[:email], "can't be blank"
  end

  test "#display_name returns formatted name" do
    @user.name = "John Doe"
    assert_equal "John Doe", @user.display_name
  end
end

请求测试:

require "test_helper"

class PostsRequestTest < ActionDispatch::IntegrationTest
  setup do
    @user = users(:active_user)
    @post = posts(:published_post)
    sign_in @user
  end

  test "GET /posts returns success" do
    get posts_path
    assert_response :success
  end

  test "POST /posts creates record" do
    assert_difference "Post.count", 1 do
      post posts_path, params: { post: { title: "New Post", body: "Content" } }
    end
    assert_redirected_to post_path(Post.last)
  end

  test "POST /posts with invalid data returns error" do
    assert_no_difference "Post.count" do
      post posts_path, params: { post: { title: "" } }
    end
    assert_response :unprocessable_entity
  end
end

策略测试:

require "test_helper"

class PostPolicyTest < ActiveSupport::TestCase
  include PolicyTestHelpers

  setup do
    @workspace = workspaces(:main_workspace)
    @admin = users(:admin_user)
    @member = users(:member_user)
    @post = posts(:workspace_post)
    Current.user = nil
  end

  test "admin can always edit" do
    with_workspace(@workspace) do
      assert policy(@admin, @post).edit?
    end
  end

  test "member requires permission to edit" do
    with_workspace(@workspace) do
      refute policy(@member, @post).edit?
      
      set_workspace_permissions(@member, @workspace, :allowed_to_edit_posts)
      assert policy(@member, @post).edit?
    end
  end

  test "scope excludes other workspace posts" do
    with_workspace(@other_workspace) do
      scope = PostPolicy::Scope.new(@admin, Post.all).resolve
      refute_includes scope, @post
    end
  end
end

性能优化检查清单

提交测试前,请确认:

  • 使用 Fixtures,而不是工厂
  • 无需数据库时,使用 User.new 而不是 User.create
  • 在内存对象上测试验证错误
  • Fixture 数据最少化(仅包含所需内容)
  • 尽可能使用请求测试,而不是系统测试
  • 将测试用的分页阈值设得较低
  • Fixture 中没有不必要的关联
  • 在测试环境中将 BCrypt 成本设为最低
  • 在测试环境中禁用日志记录
  • 适用时使用 build_stubbed 模式

应避免的反模式

  1. 测试实现细节 - 测试结果,而不是内部方法调用
  2. 设置过于复杂 - 如果设置超过 10 行,请重构为 Fixtures
  3. 测试间共享状态 - 每个测试都应相互独立
  4. 测试私有方法 - 仅测试公共接口
  5. 脆弱的断言 - 不要断言时间戳、确切错误或顺序
  6. 系统测试过多 - 仅为关键用户路径保留
  7. 缺少负向测试 - 始终测试不应成功或应被拒绝的情况
  8. 工厂级联 - 避免创建多个关联记录的工厂

运行测试

# Run all tests
bin/rails test

# Run specific file
bin/rails test test/models/user_test.rb

# Run specific test by line
bin/rails test test/models/user_test.rb:42

# Run specific test by name
bin/rails test -n "test_requires_email"

# Run directory
bin/rails test test/policies/

# Run with verbose output
bin/rails test -v

# Run in parallel
bin/rails test --parallel

# Run with coverage
COVERAGE=true bin/rails test

# Run and fail fast
bin/rails test --fail-fast

调试提示

# Print response body in request tests
puts response.body

# Print validation errors
pp @record.errors.full_messages

# Use breakpoint (Rails 7+)
debugger

# Check SQL queries
ActiveRecord::Base.logger = Logger.new(STDOUT)

# Inspect fixture data
pp users(:admin_user).attributes

评论

支持 Markdown