Rails单元测试 #

一、测试概述 #

1.1 运行测试 #

bash
rails test
rails test test/models/article_test.rb
rails test test/models/article_test.rb:10

二、模型测试 #

2.1 测试文件 #

ruby
# test/models/article_test.rb
require 'test_helper'

class ArticleTest < ActiveSupport::TestCase
  test "should be valid" do
    article = Article.new(title: 'Test', body: 'Test body')
    assert article.valid?
  end
  
  test "should require title" do
    article = Article.new(title: nil)
    assert_not article.valid?
    assert_includes article.errors[:title], "can't be blank"
  end
end

三、测试固件 #

3.1 固件文件 #

yaml
# test/fixtures/articles.yml
one:
  title: Article One
  body: Body one
  user: one

two:
  title: Article Two
  body: Body two
  user: two

3.2 使用固件 #

ruby
test "should get articles" do
  article = articles(:one)
  assert_equal 'Article One', article.title
end

四、总结 #

4.1 核心要点 #

要点 说明
assert 断言
fixtures 测试数据
rails test 运行测试

4.2 下一步 #

现在你已经掌握了单元测试,接下来让我们学习 集成测试,深入了解Rails的集成测试!

最后更新:2026-03-28